Reputation: 1618
I am working on a more complex project(10000+ LoC) and during development I encountered a problem very often.
When I add a simple variable to scope like: $scope.editing = true;
$sope.editing=false;
$scope.changeTextButtonClicked = function() {
$scope.editText;
}
<span ng-hide="editing">{{editText}}</span>
<input type="text" ng-model="editText" ng-show="editing">
<input type ="button" ng-click="changeTextButtonClicked()">
The current value of $scope.editText
can't be accessed from the controllers javascript code!
In some cases I got the old value when accessing $scope.editText
like the DOM is not updated but when printing it directly on the website with {{editText}}
it works and gets updated but in the controller I get the old value.
It happened that I have one value for {{editText}}
on the website and another value for $scope.editText
in the controller (invalid one - previous).
I solved this with adding it to a data array or any other array that is nested inside the scope:
$scope.data={}
$scope.data.editText = ...;
Can anybody explain to me why it works sometimes with $scope.variable
and sometime it doesn't and you need to add $scope.**foobar**.variable
?
Upvotes: 3
Views: 12333
Reputation: 1618
Ok i got it finally. The problem is that the $watch can be only bound to an object and observe it and not to a elementary field like string, int . boolean & co.
The bad thing is when you have a object complex structure you cant only bind it to a property but rather to the whole object that causes performance issues if its a multilevel object.
Upvotes: 0
Reputation: 189
I had the same problem time ago then i read this tutorial about scopes.
https://github.com/angular/angular.js/wiki/Understanding-Scopes
Anyway the main concept is that when you use ng-model always use a dot notation. so $scope.user={} and then $scope.user.name.
Hope it helps.
Upvotes: 2