簡體   English   中英

Angular $ scope $ watch on service function return value

[英]Angular $scope $watch on service function return value

我的websocket連接有一個服務,這個服務在函數中返回客戶端是否實際連接的實際狀態。 我簡化了我的代碼,這些代碼片段是我的問題的一個小例子:

myApp.factory('Websocket', function() {
    //the status boolean whether connected or not
    var bool = true;

    //small mock for the status change
    setInterval(function() {
        bool = !bool;
    }, 1000);

    //i've made the value of the status variable accessable in a function or the variable itself
    return {
        status: function() {
            return bool;   
        },
        var: bool
    }
});

現在我嘗試將狀態值應用於控制器中的范圍:

myApp.controller('Ctrl', function(Websocket, $scope) {
   //method 1
   $scope.status = Websocket.status();

   //method 2
   $scope.$watch(function() {
     return Websocket.status();
   }, function(newVal) {
     $scope.status = newVal;
   });
});

...但是這兩種方法都不起作用,並且不更新此html的$ scope變量:

<div ng-app="myApp">
    <div ng-controller="Ctrl">
      method1: {{status}}
    </div>
</div>

這是一個codepen: http ://codepen.io/anon/pen/bVjaBa?edit = 101

謝謝你的幫助!

這個問題就像Nikos提到的那樣:你正在改變摘要循環之外的變量值,因此angular不跟隨變化。

使用$scope.$apply是一個選項,但在這種情況下我更喜歡使用$interval而不是setInterval

myApp.factory('Websocket', function($interval) {
  var bool = true;
  $interval(function() {
    bool = !bool;
  }, 1000);

  return {
    status: function() {
        return bool;   
    },
    var: bool
  }
});

看到它在這里工作。

問題是,Angular監視的數據的任何“外部”更改都必須調用scope.$apply()讓觀察者更新(這里的觀察者是來自{{status}}表達式的UI)。 在codepen中解決方案很簡單:使服務依賴於$rootScope並在interval函數中調用$rootScope.$apply()

myApp.factory('Websocket', function($rootScope) {
    ...
    setInterval(function() {
        bool = !bool;
        $rootScope.$apply();
    }, 1000);
    ...
});

類似的東西必須與真實服務完成,關鍵概念是:(1)你必須調用$apply()和(2)無法訪問特定范圍,只需使用$rootScope

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM