Angular Directive refresh on parameter change

Luke Sapan picture Luke Sapan · Dec 31, 2013 · Viewed 126k times · Source

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 ?

Answer

Chandermani picture Chandermani · Dec 31, 2013

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