ng-repeat不动态添加新项目 [英] ng-repeat not adding new items dynamically

查看:195
本文介绍了ng-repeat不动态添加新项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Angular JS(1)的新手,并且ng-repeat遇到问题.我在Angular中使用socket.io.这是我的控制器:

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);

我可以看到它正在块内(通过console.log)进入.但是,它没有在前端显示任何内容.我的前端如下:

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>

我的理解是,如果更改模型(在这种情况下为用户),它将自动更新ng-repeat.任何帮助将不胜感激.

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.

推荐答案

在推送到数组后添加$ scope.$ apply().因为您要在角度范围之外更新模型.因此,angularjs不知道该模型已更新.有关$ scope.$ apply的更多信息 http://tutorials.jenkov.com/angularjs/watch-digest-apply.html

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

这篇关于ng-repeat不动态添加新项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆