AngularJS add variable to scope tasks

I am working on a more complex project (10000+ LoC) and during development I ran into a problem a lot.

When I add a simple variable to the 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 $scope.editText

cannot be obtained from the javascript controllers code! In some cases, I got the old value when accessing $scope.editText

, since the DOM is not updated, but when printing it directly to the website with {{editText}}

it, it works and updates, but in the controller I get the old value.

It so happened that I have one value for {{editText}}

in the website and another value for $scope.editText

in the controller (invalid - the previous one).

I solved it by adding it to the data array or any other array that is nested in the scope:

     $scope.data={}
     $scope.data.editText = ...;

      

Can someone explain to me why it sometimes works with $scope.variable

, and sometime it doesn't and you need to add $scope.**foobar**.variable

?

+3


source to share


2 answers


I had the same thing as me then I read this tutorial about clouds.

https://github.com/angular/angular.js/wiki/Understanding-Scopes



In any case, the basic idea is that when using the ng model, always use dot notation. so $ scope.user = {} and then $ scope.user.name.

Hope it helps.

+2


source


Ok, finally. The problem is that $ watch can only be bound to an object and watched, and not to an elementary field of type string, int. boolean and co.



It is bad when you have a complex object structure that you cannot only bind to a property, but rather to the entire object, which causes performance issues if it is a multi-level object.

0


source







All Articles