AngularJs向ng-repeat添加新数据

时间:2019-04-21 17:08:29

标签: angularjs

我创建了一个小应用程序。我使用实时数据库。首先,我使用查询从数据库中获取数据。当一条记录添加到数据库中时。我可以得到这些数据。但是我必须将新数据添加到现有数据中。我该如何追加?

HTML

<tr ng-repeat="i in result track by $index">
    <td>{{i.id}}</td>
    <td>{{i.category}}</td>
    <td>{{i.status}}</td>       
</tr>

JS

var app = angular.module('socket', []); 
app.controller('homeController', function ($scope) {        
    var socket = io.connect('http://localhost:3000');
    socket.on('list', function (data) {     
        $scope.result =  data;
        if (!$scope.$$phase) $scope.$apply();   
    });
});

数据

First query result

data = [
        {id:1, category:2, status:1},
        {id:2, category:1, status:2}
       ];

New data result

newData = [{id:3, category:1, status:2}];

1 个答案:

答案 0 :(得分:1)

Try this:

var app = angular.module('socket', []); 
app.controller('homeController', function ($scope) {        
    var socket = io.connect('http://localhost:3000');
    $scope.result = []
    socket.on('list', function (data) {     
        $scope.result = $scope.result.concat(data);
        if (!$scope.$$phase) $scope.$apply();   
    });
});