AngularJs directory link function cannot modify a variable defined in a controller scope

I am trying to create a directive with a link where it can change the "varName" in scope (ie in the input tag). Note that the directive template has the same "varName" as the controller and does not use the scope property.

Here's what happened:

Case 1: if I click on a user element, the function "runFn" defined in the scope $ scope is called, however, "varName" does not change.

Case 2: If I click on the div tag, the function "runFn" is also called and "varName" is changed.

I tried 3 approaches, but I can not get the link function to change the value of "varName". Can someone explain why n provide a solution please? Thanks.

code:

<body ng-app="moduleA"> <div ng-controller="ctrlA"> <input type="text" ng-model="varName"> <custom></custom> <div ng-click="runFn()">click for new value</div> </div> <script> window.onload=(function(){ "use strict"; var app = angular.module('moduleA', []); app.controller("ctrlA", function($scope){ $scope.varName = "old value"; $scope.runFn = function(){ $scope.varName = "new value"; console.log("run fn"); }; }); app.directive("custom", function(){ return { restrict: "E", template: '<div>{{varName}}</div>', replace: true, link: function(s, e, a){ e.on("click", function(){ s.varName = "new value"; //didn't work s.runFn(); //didn't work s.runFn.call(s); //didn't work }); } }; }); })(); // end windows onload </script> </body> 
+6
source share
2 answers

I think all you forget is to call $ apply when you do updates to update the user interface.

 e.on("click", function(){ //Call $apply to ensure a $digest loop // get kicked off s.$apply(function(){ s.varName = "new value"; }); }); 
+13
source

The click function is executed in angular. You need to handle the click event in angular. Change your directive as follows

 app.directive("custom", function(){ return { restrict: "E", template: '<div ng-click="divClick()">{{varName}}</div>', replace: true, link: function(s, e, a){ s.divClick = function(){ s.varName = "new value"; s.runFn(); s.runFn.call(s); } } }; }); 

Jsbin

+1
source

All Articles