Вопрос

Let's say I have this array in $scope :

userList = [ { 
    firstName : 'John', 
    visits : 1, 
    colors : { red : 1, yellow : 0 } 
} ];

The template looks like :

<ul>
    <li ng-repeat="user in userList">
        {{user.firstName}} - {{user.visits}} <br/>
        (red: {{user.colors.red}}; yellow: {{user.colors.yellow}})<br/>
        {{user.foo}}
    </li>
</ul>

Then I receive new data from the sever :

newUserList = [ { 
    firstName : 'John', 
    visits : 2, 
    colors : { red : 5, yellow : 1 },
    foo : 'bar'
} ];

To make the updates effective I'm actually doing a simple $scope.userList = newUserList;

The problem is that doing it this way clears the whole element before setting the new values. So the template becomes <ul></ul> before returning to <ul><li>(...data...)</li></ul>

I'd like to simply update/push/add the new values. A kind of merge/extend that doesn't change things that are up to date. I guess there's a proper way to do it but couldn't find a right answer yet.

Это было полезно?

Решение

You can use track by to specify how the objects in the collection are associated with the DOM elements.

For example:

<li ng-repeat="user in userList track by user.firstName">

When using this and assigning a new array of users, as long as the tracked property of a user object is the same as previously, it will be considered the same object and Angular will update the existing DOM element instead of recreating it.

Note that the value of the property you are tracking must be unique, so obviously user.firstName would not be a good choice.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top