Angularjs ng-repeat list is not updated when adding / removing an item

There is a list of users extracted from rest api. Here is the template

<div ng:controller="UserController"> <a ng-click="createUser()">Create User</a> <div ng-view> <ul> <li ng-repeat="user in users"> {[{user.first_name}]} {[{user.last_name}]} </li> </ul> </div> </div> 

JS:

 function UserController($scope, User, Group){ $scope.users = User.query(); $scope.createUser = function(){ //$scope.users = null; //$scope.users.pop(); //$scope.users.push(new User({id:'5'})); console.log($scope.users); } } 

Service: http://dpaste.com/1065440/

All users are correctly loaded and specified. The problem is that I cannot manipulate the displayed list at all. No matter what I do, push, pop or set to null. The list does not change in the template. However, the last log statement shows the changes, it prints, for example. NULL if the users array is set to null.

Any ideas what the problem is?

+6
source share
2 answers

The object you insert into the array must be an instance of User

 function UserController($scope, User){ $scope.users = User.query(); $scope.createUser = function(){ $scope.users.push(new User({first_name:'Bob', last_name: 'Schmitt'})); } } 

So use new User({})

From our conversation, it seems that the problem was in routing. The same external controller was assigned to the partial one, which was loaded into the ng-view . Removing ng:controller="UserController" and moving the createUser button to a partial solution to the problem, but if you really need to call the createUser method from outside the ng-view , then all the data associated with it must be in the external controller. Thus, you can save the external controller as it is and change your route to use an empty placeholder controller.

+5
source

make sure createUser is called. IE ng-click or something else.

 <button type="button" ng-click="createUser()">Create User</button> 

The push function looks right, but your html binding looks wrong. These must be double curly braces.

 <li ng-repeat="user in users"> {{user.first_name}} {{user.last_name}} </li> 

Added an example that I used earlier when adding an object.

 <div ng-app="main"> <div ng-controller="MyCtrl"> <button ng-click="add()" >Add</button> <div id="container"> <div ng-repeat="test in tests>{{test.name}}</div> </div> </div> </div> $scope.tests = {}; $scope.add = function() { var newTest = {name: 'Test Message'}; $scope.tests.push(newTest); }; 
+3
source

All Articles