logesh
logesh

Reputation: 2672

Angular directive not applied on change of the value

I have a directive like

testApp.directive('changeValue', function(){
    alert("coming");
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            element.text(attrs.val);
        },
        replace: true
    };
});

and I have my views as follows

<change-value val="{{test.val}}"/>

When I refresh my page, I could see the values and I get the alerts. But when the value is changed I don't get it applied to the directive but it binds to the view as I could see it being changed outside when simply called like

<span>{{test.val}}</span>

I am not sure how this works. Thanks in Advance!

Upvotes: 2

Views: 873

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388446

In your code, the link function is executed only once so the value is updated only when the directive instance is created. Since you want to have a watch of its value and keep updating the text you can use $observe()

var app = angular.module('my-app', [], function() {})

app.controller('AppController', function($scope) {
  $scope.test = {
    val: "Welcome"
  };
});

app.directive('changeValue', function() {
  return {
    restrict: 'E',
    link: function(scope, element, attrs) {
      attrs.$observe('val', function() {
        element.text(attrs.val);
      })
    },
    replace: true
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="my-app" ng-controller="AppController">
  <change-value val="{{test.val}}"></change-value>
  <input ng-model="test.val" />
</div>

Upvotes: 3

Related Questions