TMichel
TMichel

Reputation: 4442

AngularJS: nested array and view update

I'm having problems updating the view after an Array inside an Array is updated in the $scope.

First i check if the Array member already exists:

$scope.myArray = [];
if(typeof $scope.myArray[someIndex] == 'undefined') {
  $scope.myArray[someIndex] = {
    name: someName,
    data: []
  };
}

Then push to $scope.myArray[someIndex].data:

$scope.myArray[someIndex].data.push(dataContent);

At this point the view does not update.

Of course if i directly push to $scope.myArray it does. Any suggestions?

Edit: Fiddle here

Upvotes: 3

Views: 1881

Answers (3)

Alagarasan M
Alagarasan M

Reputation: 907

This works:

HTML,

<div ng-app>
    <div ng-controller="NestedCtrl">
        <article ng-repeat="member in myArray">
            {{member.name}}
            <article ng-repeat="next in member.data">
                {{next.nested}}
            </article>
        </article>
    </div>
</div>

Angular JS:

function NestedCtrl($scope) {

    $scope.myArray = [];

    var callMe = function(){
      if(typeof $scope.myArray[0] == 'undefined') {
          $scope.myArray[0] = {
              name: 'Hello',
              data: []
          };
      }

      $scope.myArray[0].data.push({nested : 'yay'});   
    }

    callMe();
}

Upvotes: 0

TMichel
TMichel

Reputation: 4442

It was simpler than it looked.

Based on the response here i am setting an associative array which allows set string keys. If you declare your array as =[] you simply cannot set strings as keys.

So i just changed my declaration $scope.myArray=[] to $scope.myArray={} and voilà, it works.

Upvotes: 1

Yaron Schwimmer
Yaron Schwimmer

Reputation: 5357

Try:

if(typeof $scope.myArray[someIndex] == 'undefined') {
   $scope.$eval(function(){
     $scope.myArray[someIndex] = {
       name: someName,
       data: []
     };
     $scope.myArray[someIndex].data.push(dataContent);
   });       
}

Upvotes: 0

Related Questions