Search code examples
javascriptangularjsangularjs-directiveangularjs-scopeangularjs-watch

Update directive when scope variable is updated in angularjs


I have created a directive in which i am parsing a variable "count". In my page there is a dropdown and "count" gets updated whenever dropdown value is changed. I have created a directive to show "count". How can i update the directive whenever dropdown value is changed.

Code:

<stats count="{{self.shortenedCountArray[2].orignalCount}}"></stats>

Directive code:

(function() {
    'use strict';

    angular
       .module('app.pages')
       .directive('stats', stats);
   
       stats.$inject = [ '$rootScope']

   function stats( $rootScope) {
       return {
           restrict: 'E',
           scope: {},
           templateUrl: 'k2-modules/js/directives/templates/statsTemplate.html',
           link: (scope, element, attrs) => {
            scope.count = attrs.count;
           }
       }
   }
   
})();

Any help will be appreciated.


Solution

    • Watchers requires some time so if you dont want to next cycle/trigger use $apply

    • and adding timeout clasure may need at some situations.

      link: (scope, element, attrs) => {
        setTimeout ... if needed
         scope.$apply(function () {
          scope.count = attrs.count;
         });