我正在使用Pusher for Angular Webapp进行实时应用。我需要在其他会话中从表单添加项目时向阵列产品添加新项目。在我的sessión它的作品。在另一个会话中,如果将数据添加到阵列但未在ng-repeat中显示,则获得数据。
控制器:
.controller('MainCtrl', ['$scope','Products',function($scope,Products) {
$scope.products = Products.getAll();
var pusher = new Pusher('MY KEY', {
encrypted: true
});
$scope.addProduct = function(product){
Products.addProduct(product);
}
var callback = function(data) {
$scope.products.push(data.NewProduct);
console.log($scope.products);
};
var channel = pusher.subscribe('products');
channel.bind('addProduct', callback);
}]);
查看:
<tbody>
<tr ng-repeat="product in products track by product.id">
<td >{{product.name}}</td>
<td>{{product.unity}}</td>
<td>{{product.price}}</td>
<td>
<button>
Edit
</button>
<button>
Delete
</button>
</td>
</tr>
</tbody>
答案 0 :(得分:0)
$evalAsync稍后在当前作用域上执行表达式。
所以在代码
中添加$ evalAsync到回调函数.controller('MainCtrl', ['$scope','$evalAsync','Products',function($scope,$evalAsync, Products) {
$scope.products = Products.getAll();
var pusher = new Pusher('MY KEY', {
encrypted: true
});
$scope.addProduct = function(product){
Products.addProduct(product);
}
var callback = function(data) {
$scope.products.push(data.NewProduct);
console.log($scope.products);
};
var channel = pusher.subscribe('products');
channel.bind('addProduct', $evalAsync(callback));
}]);
答案 1 :(得分:0)
我是这样做的:
var callback = function(data) {
$scope.$apply(function(){
$scope.products.push(data.Producto);
});
console.log($scope.products);
};