[英]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
謝謝你的幫助!
問題是,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.