0

I have two arrays in my controller and a third array which is formed by concatenating the first two arrays.

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

var MainController = app.controller('MainController', function($scope) {
  $scope.dogs = ['Beagle', 'Poodle', 'Boxer'];
  $scope.cats = ['Maine Coon', 'Ragdoll', 'Bengal'];
  $scope.pets = $scope.dogs.concat($scope.cats);

  $scope.createDog = function() {
    $scope.dogs.push('Rottweiler');
  };
});

I then output all this data using ng-repeat.

<h3>Dogs ({{dogs.length}})</h3>
<ul>
  <li ng-repeat="dog in dogs">{{dog}}</li>
</ul>
<button ng-click="createDog()">Add a dog</button>
<hr>
<h3>Cats ({{cats.length}})</h3>
<ul>
  <li ng-repeat="cat in cats">{{cat}}</li>
</ul>
<hr>
<h3>Pets ({{pets.length}})</h3>
<ul>
  <li ng-repeat="pet in pets">{{pet}}</li>
</ul>

When I click the button and add a dog to the $scope.dogs array, the list of pets never gets updated.

Here's the code on Plunker

How can I concat two collections of objects while preserving angular's bindings so that the pets will update?

David Tuite
  • 22,258
  • 25
  • 106
  • 176

2 Answers2

2

You can solve this, by defining $scope.pets as a function, so it's an expression and updates when ever a used $scope variable within is being updated: http://plnkr.co/edit/6DyKeN?p=preview

$scope.pets = function() {
    return $scope.dogs.concat($scope.cats);
};
naeramarth7
  • 6,030
  • 1
  • 22
  • 26
1

This works:

For pets to be updated change your JS function to,

$scope.createDog = function() {
   $scope.dogs.push('Rottweiler');
   $scope.pets = $scope.dogs.concat($scope.cats);

};

Since you have pushed the same name ie.;'Rottweiler'. It will not get rendered by ng-repeat on the screen due to duplicates creation, so use

For dogs,

<li ng-repeat="dog in dogs track by $index">{{dog}}</li>

For Pets,

<li ng-repeat="pet in pets track by $index">{{pet}}</li>
Alagarasan M
  • 907
  • 8
  • 16