3

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.