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; } } } });
Then when having:
<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>
How can I get the access the scope.changeLabel of extLabel2 in a controller?
Does it make sense?
Does this work for you?
angular.directive('extLabel', function() { return { restrict: 'E', scope: { api: '=' }, link: function(scope, iElement, iAttrs) { scope.api = { doSomething: function() { }, doMore: function() { } }; } }; });
From containing parent
<ext:label api="myCoolApi"></ext:label>
And in controller
$scope.myCoolApi.doSomething(); $scope.myCoolApi.doMore();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With