Yehia A.Salam
Yehia A.Salam

Reputation: 2028

Angular Binding in Object Property

How can I make the binding works for object properties. For example in my controller I have:

$scope.reviews = {
  rating_summary: 4,
  items: [ { title: 'A Title'}, etc...  ]
}

And in my view:

<li ng-repeat="review in reviews.items">

Now, whenever i change the reviews variables in the controller, nothing is updated:

$scope.reviews = [new updated reviews]

Probably beacause angular is listening for changes on the old reference of $scope.reviews.

There are two solutions for the binding to work, but both are not very clever:

  1. Attach the items to the scope directly, so it would be $scope.items = $scope.reviews.items, Now whenever the items are changed they would be updated.
  2. User angular.copy to keep the destination reference, so angular.copy({items: []}, $scope.reviews);

Are there any other solutions to accomplish this other than the above.

Upvotes: 0

Views: 210

Answers (1)

appdroid
appdroid

Reputation: 565

It should work there must be some mistake while updating the object/items Please refer this Plunker

$scope.reviews = {
    rating_summary: 4,
    items: [ { title: 'A Title'}, { title: 'B Title'}  ]
  };

  $scope.changeItems = function(){
    $scope.reviews.items = [ { title: 'A Title'}, { title: 'B Title'},
                             { title: 'C Title'}];
  };

  $scope.changeObject = function(){
    $scope.reviews = {
    rating_summary: 4,
    items: [ { title: 'A Title'}, { title: 'B Title'}, { title: 'D Title'}  ]
  };

Upvotes: 1

Related Questions