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"; </script> </body>
source share