ng-repeat not adding new items dynamically

 ̄綄美尐妖づ 提交于 2019-12-12 03:54:34

问题


I am new to Angular JS (1) and I am having issues with ng-repeat. I am using socket.io with Angular. Here is my controller:

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

function mainController($scope) {

    var socket = io.connect();
    socket.on('message', function(data){
        $scope.users.push({'Name': 'yeh'});
        console.log($scope.users);
    });

    $scope.users = []; //if I put stuff here and comment out socket stuff, it shows in the front-end
};

messagingApp.controller('mainController',mainController);

I can see that it is going inside that on block (via console.log). However, it is not displaying anything to the front-end. My front-end is as follows:

<body ng-controller="mainController">

<div ng-repeat="user in users">
    <p>{{ user.Name }}</p>
</div>

My understanding is that if you change the model (users in this case), it should automatically update the ng-repeat. Any help would be appreciated.


回答1:


Add $scope.$apply() after pushing to the array. Because you are updating the model outside of the angular scope. So the angularjs doesnot know the model has been updated. More about $scope.$apply http://tutorials.jenkov.com/angularjs/watch-digest-apply.html




回答2:


you are pushing the object in array and try to iterate Array. So you should specify the position.

<body ng-controller="mainController">
    <div ng-repeat="user in users">
        <p>{{ user[$index].Name }}</p>
    </div>

or try this..

socket.on('message', function(data){
         $scope.users.data.push({'Name': 'yeh'});
        console.log($scope.users.data);
    });

     $scope.users = {data:[]};





<div ng-repeat="user in users.data">
        <p>{{ user.Name }}</p>
    </div>


来源:https://stackoverflow.com/questions/41179103/ng-repeat-not-adding-new-items-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!