有一个角度的指令是一个可重用组件,最好的做法是公开一个可以从控制器访问的公共API?
因此,当有多个组件实例时,您可以从控制器访问
因此,当有多个组件实例时,您可以从控制器访问
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?
是否有意义?
这对你工作吗?
angular.directive('extLabel',function() {
return {
restrict: 'E',scope: {
api: '='
},iAttrs) {
scope.api = {
doSomething: function() { },doMore: function() { }
};
}
};
});
从包含父级
<ext:label api="myCoolApi"></ext:label>
和在控制器
$scope.myCoolApi.doSomething(); $scope.myCoolApi.doMore();