简体   繁体   中英

Angular JS how to update scope variable inside another scope variable

I am bulding a list using ng-repeat from array of objects. One of the property in array is a boolean that will go in ng-show of each element I am building using this array. Array itself is a scope variable too.

Now I want to update display property only. Is it possible?

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.displayThird = false;

  $scope.list = [
    {
      text: "One",
      display: true
    },
    {
      text: "Two",
      display: true
    },
    {
      text: "Three",
      display: $scope.displayThird
    },
    {
      text: "Four",
      display: true
    }
  ];

  /* I want this function to update my display property */
  $scope.display = function() {
    $scope.displayThird = true;
  }
});

http://plnkr.co/edit/kF1M1fWyeCcrfcUY3Aqu?p=preview

This is a common misconception: When you assign an expression to a variable in Javascript , only the value of the expression gets assigned. No binding gets created. On the contrary, expressions in Angular templates do create bindings.

Therefore in your case the $scope.list[2].display gets assigned the value false and knows nothing how this value was created.

The correct way to do this in Angular is with a watch:

$scope.$watch("displayThird", function(newval) {
    $scope.list[2].display = newval;
});

This is what Angular does under the hoods with its templates, only you have to do it manually in Javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM