angularjs - Angular Directive: use $watch or pass in binded value -


i have controller calls service returning list of courses. each course has property called 'percentagedone'

i want assign css div depending on value.

there 2 ways have found this. there more, newbie @ angular. thing not sure best way. in terms of performance , general best angular practice. realize use ng-class, using exercise learn angular.

so div

<div ng-repeat="e in courses">   <div completion-color="{{e.percentagedone}}"></div> </div> 

with directive

myapp.directive('completioncolor', function () {   return {    restrict: 'a',    link: function (scope, el, attrs) {     var doneperc = attrs['completioncolor'];      if (doneperc < 33) {       el.addclass('progress-bar-danger');      }      else if (doneperc >= 33 && newval < 66) {       el.addclass('progress-bar-warning');      }      else if (doneperc >= 66) {       el.addclass('progress-bar-success');      }    }   }; }); 

or way

<div completion-color="e.percentagedone"></div> 

and js

myapp.directive('completioncolor', function () {     return {         restrict: 'a',         link: function (scope, el, attrs) {             scope.$watch(attrs['completioncolor'], function (newval) {                 if (newval < 33) {                     el.addclass('progress-bar-danger');                 }                 else if (newval >= 33 && newval < 66) {                     el.addclass('progress-bar-warning');                 }                 else if (newval >= 66) {                     el.addclass('progress-bar-success');                 }             });         }     }; }); 

i don't have put {{}} in directive, in general data not change much. not sure need use $.watch.

i'd $watch last thing should use here.

i myself see no problem using {{}}, that's for. have option if want, use one time binding (https://docs.angularjs.org/guide/expression) if you're using angular 1.3.x , way you're improving performance, since angular doesn't keep watch that:

<div ng-repeat="e in courses">   <div completion-color="{{::e.percentagedone}}"></div> </div> 

and work scope in directive (you can use isolated well):

scope: {     completioncolor: "@" }, 

now can use scope.completioncolor in link function.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -