javascript - AngularJS ng-repeat key-value pairs to directive -


i have following html:

<p data-ng-repeat="(aname, arating) in content.ratings">     <div star-directive rating="arating"></div> </p> 

arating object. directive picks "arating" text rating variable.

what directive have able use arating object?

attrs.rating expression string set attribute. can evaluate against scope scope.$eval().

angular.module('your-module') .directive('stardirective', function() {   return {     restrict: 'a',     scope: false,     link: function(scope, element, attrs) {       var ratingexpression = attrs.rating;       var rating = scope.$eval(attrs.rating);        // rating.     }   } }); 

scope: false default value, means directive not create new scope , shares scope parent.

however, above directive won't know when arating updated. if want update directive arating changes, can use isolate scope , data binding.

angular.module('your-module') .directive('stardirective', function() {   return {     restrict: 'a',     scope: {       rating: '=rating'     },     link: function(scope, element, attrs) {       // `rating` object available `scope.rating` , keep updated.     }   } }); 

this create new scope directive , bind arating newly created scope's rating property. new scope isolated parent scope, means not prototypically inherit parent scope. it's toolkit creating reusable components.

the = sign bidirectionally binds rating attribute rating property of directive's scope. means scope.rating updated when arating changes , arating updated when scope.rating changes.

if interested in isolate scope, see angular's documentation more details.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -