Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Directive refresh on parameter change

I have an angular directive which is initialized like so:

<conversation style="height:300px" type="convo" type-id="{{some_prop}}"></conversation> 

I'd like it to be smart enough to refresh the directive when $scope.some_prop changes, as that implies it should show completely different content.

I have tested it as it is and nothing happens, the linking function doesn't even get called when $scope.some_prop changes. Is there a way to make this happen ?

like image 938
Luke Sapan Avatar asked Dec 31 '13 11:12

Luke Sapan


2 Answers

Link function only gets called once, so it would not directly do what you are expecting. You need to use angular $watch to watch a model variable.

This watch needs to be setup in the link function.

If you use isolated scope for directive then the scope would be

scope :{typeId:'@' }

In your link function then you add a watch like

link: function(scope, element, attrs) {     scope.$watch("typeId",function(newValue,oldValue) {         //This gets called when data changes.     });  } 

If you are not using isolated scope use watch on some_prop

like image 194
Chandermani Avatar answered Sep 19 '22 18:09

Chandermani


What you're trying to do is to monitor the property of attribute in directive. You can watch the property of attribute changes using $observe() as follows:

angular.module('myApp').directive('conversation', function() {   return {     restrict: 'E',     replace: true,     compile: function(tElement, attr) {       attr.$observe('typeId', function(data) {             console.log("Updated data ", data);       }, true);      }   }; }); 

Keep in mind that I used the 'compile' function in the directive here because you haven't mentioned if you have any models and whether this is performance sensitive.

If you have models, you need to change the 'compile' function to 'link' or use 'controller' and to monitor the property of a model changes, you should use $watch(), and take of the angular {{}} brackets from the property, example:

<conversation style="height:300px" type="convo" type-id="some_prop"></conversation> 

And in the directive:

angular.module('myApp').directive('conversation', function() {   return {     scope: {       typeId: '=',     },     link: function(scope, elm, attr) {        scope.$watch('typeId', function(newValue, oldValue) {           if (newValue !== oldValue) {             // You actions here             console.log("I got the new value! ", newValue);           }       }, true);      }   }; }); 
like image 26
j8io Avatar answered Sep 21 '22 18:09

j8io