javascript - Angular directive not applied on change of the value -
i have directive like
testapp.directive('changevalue', function(){ alert("coming"); return { restrict: 'e', link: function (scope, element, attrs) { element.text(attrs.val); }, replace: true }; });
and have views follows
<change-value val="{{test.val}}"/>
when refresh page, see values , alerts. when value changed don't applied directive binds view see being changed outside when called like
<span>{{test.val}}</span>
i not sure how works. in advance!
in code, link function executed once value updated when directive instance created. since want have watch of value , keep updating text 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>
Comments
Post a Comment