我现在有一些基本的角度问题。我只写了一个服务,以5秒为间隔读取外部设备的温度。该服务将新温度保存到变量中并通过返回语句公开。这看起来有点这个(简化代码):AngularJS通过服务自动更新控制器数据
angular.service("tempService", ["$interval", function ($interval) {
//revealing module pattern
var m_temp = 0,
requestTemp = function() {//some logic here},
onResponseTemp = function (temp) {
m_temp = temp;
},
//some other private functions and vars ...
foo = bar;
//request new temperture every 5s, calls onResponseTemp after new data got received
$interval(requestTemp, 5000);
return {
getTemp = function(){return m_temp;}
}
}]);
我使用一个控制器从这样的服务获取数据:
angular.controller("tempCtrl", ["$scope", "tempService", function ($scope, tempService) {
$scope.temp = tempService.getTemp();
}]);
在我看来,我访问这样的:
<div ng-controller="tempCtrl">
<p>{{temp}}</p>
</div>
但我只得到0,并且值永不改变。我试图实现一个自定义的Pub/Sub模式,以便在新的温度下,我的服务会触发一个事件,我的控制器正在等待更新示波器温度。这种方法工作得很好,但我不确定这是否是角度带来数据绑定的方式,我认为这种简单的方法必须自行工作;)
帮助真的很感激。
返回一个对象而不是一个原始的技巧。谢谢! – Fidel90 2014-10-02 10:19:05
只是为了确认,当服务更新时,控制器中的数据会完全更新,然后您访问控制器或UI中的服务值或功能?你可以或你会做$ scope.startTemp = tempService.startTemp,然后调用UI或控制器调用函数,如$ scope.startTemp()而不是传递整个服务? – mtpultz 2014-10-09 05:17:16