如何从作为可重用组件的指令公开公共 API? [英] How to expose a public API from a directive that is a reusable component?

查看:33
本文介绍了如何从作为可重用组件的指令公开公共 API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 angular 中有一个可重用组件的指令,公开可从控制器访问的公共 API 的最佳实践是什么?因此,当组件有多个实例时,您可以从控制器访问

Having a directive in angular that is a reusable component, what is the best practice to expose a public API that can be accessed from the controller? So when there are multiple instances of the component you can have access from the controller

angular.directive('extLabel', function {
    return {
        scope: {
            name: '@',
            configObj: '='
        },
        link: function(scope, iElement, iAttrs) {
            // this could be and exposed method
            scope.changeLabel = function(newLabel) {
                scope.configObj.label = newLabel;
            }
        }
    }
});

然后当有:

<ext-label name="extlabel1" config-obj="label1"></ext-label>
<ext-label name="extlabel2" config-obj="label2"></ext-label>
<ext-label name="extlabel3" config-obj="label3"></ext-label>

如何在控制器中访问 extLabel2 的 scope.changeLabel?

How can I get the access the scope.changeLabel of extLabel2 in a controller?

有意义吗?

推荐答案

这对您有用吗?

angular.directive('extLabel', function() {
    return {
        restrict: 'E',
        scope: {
            api: '='
        },
        link: function(scope, iElement, iAttrs) {
            scope.api = {
                    doSomething: function() { },
                    doMore: function() { }
                };
        }
    };
});

来自包含父级

<ext:label api="myCoolApi"></ext:label>

在控制器中

$scope.myCoolApi.doSomething();
$scope.myCoolApi.doMore();

这篇关于如何从作为可重用组件的指令公开公共 API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆