Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expose a public API from a directive that is a reusable component?

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?

like image 298
Andres Valencia Avatar asked Aug 30 '13 12:08

Andres Valencia


1 Answers

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(); 
like image 146
Andrej Kaurin Avatar answered Sep 29 '22 17:09

Andrej Kaurin