Reputation: 2740
I have following line of code.
HTML
...
<html ng-app="myApp">
....
<div ng-controller="myController">
<div ng-model="info.myField"></div>
<a href="#" my-update field="info.myField">Update Me</a>
</div>
JS
var app = angular.module("myApp",[]){
app.controller("myController", ['$scope',function($scope){
$scope.info = {
myField = "init value"
};
}]);
app.directive("myUpdate",function() {
return {
restrict: "A",
scope : {
field:"="
},
link: function(scope, elem, attrs){
scope.field = "Updated in link"; //Line A
elem.bind("click",function() {
scope.field = "Updated on click"; //Line B
});
}
};
});
When I run this code, controller's info.myField is updated to "Updated in link" (as done in Directive's Line A). When I click "Update Me" anchor, Directive's Line B is executed but controller's info.myField is not updated.
Why info.myField is not being updated in click event? Am I missing something?
Upvotes: 2
Views: 80
Reputation: 22943
Jayantha is correct, you should call $apply()
to make it work. But you might ask why you should have to do that. The reason for this is that the click
event happens outside of Angulars world. So Angular doesn't know that the click
has happened, and you need to tell Angular about it, which you do by calling scope.$apply()
. When you have a ng-click
that calls a method on your scope, you don't have to call $apply()
because it's Angular that calls that method for you, which means that Angular knows about it, and will call $apply()
for you.
Upvotes: 4
Reputation: 21376
try to do like this,
elem.bind("click",function() {
$scope.$apply({
scope.field = "Updated on click"; //Line B
});
});
Upvotes: 3