I am trying to create a directive with a link function where it can change the "varName" in the scope (i.e. in the input tag). Note the directive template has same "varName" as in the controller & no scope property is used.
Here is what happened:
Case 1: If I click the custom element, the "runFn" function defined in the $scope gets called, however the "varName" is not changed.
Case 2: If I click the div tag, the "runFn" function also gets called AND the "varName" is changed.
I have tried 3 approaches but can't seem to get the link function to change the "varName" value. 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>