2017-06-15 64 views
0

我使用Pusher爲Angular Webapp的實時應用程序。當其他會話中的其他表單添加項目時,我需要向陣列產品添加新項目。在我的論文中,它是有效的。在另一個會話中,如果將數據添加到數組中但在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

可能是與角消化週期的問題!嘗試在'$ evalAsync'中包裝您的'回調函數' –

+0

感謝@ GangadharJannu,但我仍然不明白我該怎麼做。 –

+0

看到我的[answer](https://stackoverflow.com/a/44582823/3543808) –

回答

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)); 
}]); 
+0

非常感謝你! –

+0

該解決方案是否適合您? –

+0

不,我沒有這樣說: VAR回調=功能(數據){$ 範圍$申請(函數(){$ scope.products.push(data.Producto); }); console.log($ scope.products); }; –

0

我做了這樣的:

var callback = function(data) { 
      $scope.$apply(function(){ 
       $scope.products.push(data.Producto); 
      }); 
      console.log($scope.products); 
     };