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

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

问题描述

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

var messagesApp = angular.module('messagingApp', []);函数 mainController($scope) {var socket = io.connect();socket.on('message', function(data){$scope.users.push({'Name': 'yeh'});控制台日志($scope.users);});$scope.users = [];//如果我把东西放在这里并注释掉套接字的东西,它会显示在前端};messagesApp.controller('mainController',mainController);

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

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

我的理解是,如果您更改模型(在本例中为用户),它应该会自动更新 ng-repeat.任何帮助将不胜感激.

解决方案

在推送到数组后添加 $scope.$apply().因为您正在角度范围之外更新模型.所以 angularjs 不知道模型已经更新.更多关于 $scope.$apply http://tutorials.jenkov.com/angularjs/watch-digest-apply.html

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.

解决方案

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天全站免登陆