Reputation: 693
I am trying to change directive controller's $scope with ng-click.
I have one simple button:
<button ng-click="showEnterKeyField = !showEnterKeyField">btn {{showEnterKeyField}}</button>
This code works. I mean, we will se something like ( as button .text() ):
btn true
btn false
btn true
... etc
But in controller we have:
$scope.$watch('showEnterKeyField', function(val) {
console.log(val);
}, true);
And in console there are no logs at all.
Next thing that I was thying to do is to run some test()
fn inside of ng-click
:
<button ng-click="test()">btn {{showEnterKeyField}}</button>
And for my surprise this code works exactly same as above one:
btn true
btn false
btn true
... etc
This time i see records in the console.
Why does the scope is not changing in the first scenario? Thanks.
UPDATE
Of course, here is my $scope.test()
:
$scope.test = function() {
$scope.showEnterKeyField = !$scope.showEnterKeyField;
};
Upvotes: 0
Views: 54
Reputation: 6250
You need to define the attribute (in this case showEnterKeyField
) on you controllers scope first, so it will be inherited by the ngClick directive. If it's not defined, the ngClick directive will create the attribute on it's own child scope - so you cannot watch it from within your controllers (parent) scope.
Simply add the following to your controller:
$scope.showEnterKeyField = false; // or some other initial value
See: JS Bin
Upvotes: 1