Join the Stack Overflow Community
Stack Overflow is a community of 6.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
up vote 2 down vote accepted

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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.