我有一个服务为我的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;
});
});
...但是这两种方法不工作,没有为这个网站更新$范围变量:
<div ng-app="myApp">
<div ng-controller="Ctrl">
method1: {{status}}
</div>
</div>
这是一个codepen:http://codepen.io/anon/pen/bVjaBa?editors=101
感谢您的帮助!
感谢您的帮助! – Sim
我会使用$ rootScope。$ digest而不是$ apply - 因为您所做的只是跳过try/catch语句以达到相同的结果。 [源(https://github.com/angular/angular.js/blob/v1.2.16/src/ng/rootScope.js#L886)。不是很昂贵,但是,没有真正的理由这样做。 –