Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
 
is this what you are trying to do? plnkr.co/edit/1S4AWMQ1gLUr9li03Xje?p=preview –  charlietfl Nov 17 '13 at 13:41
 
@charlietfl - yes, ultimately this is what I wanted to achieve. But I wanted something where I don't need to specify array index, incase I don't know it. Nikos' answer helped me realise why I couldn't do it the way I wanted. –  Yuri Nov 17 '13 at 13:55
 
you can pass in the specific item also, then get it's index from within controller. var idx= $scope.list.indexOf(item) –  charlietfl Nov 17 '13 at 14:12
add comment

1 Answer

up vote 1 down vote accepted

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.

share|improve this answer
 
Thanks very much. I was hoping there's some secret angular method to let it know that this is a scope variable to watch. Thanks for a quick response. –  Yuri Nov 17 '13 at 13:50
add comment

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.