目前我在 Angular 方面遇到了一些基本问题。我刚刚编写了一个以五秒的间隔读取外部设备温度的服务。该服务将新温度保存到变量中,并通过返回语句公开它。这看起来有点像这样(简化的代码):
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;}
}
}]);
我使用 Controller 从服务中获取数据,如下所示:
angular.controller("tempCtrl", ["$scope", "tempService", function ($scope, tempService) {
$scope.temp = tempService.getTemp();
}]);
在我看来,我是这样访问它的:
<div ng-controller="tempCtrl">
<p>{{temp}}</p>
</div>
但我只得到 0 并且该值永远不会改变。我尝试实现自定义发布/订阅模式,以便在新的温度下我的服务会触发一个事件,我的 Controller 正在等待更新示波器上的温度。这种方法工作得很好,但我不确定这是否是正确的方法,因为 Angular 带来了数据绑定(bind),我认为这种简单的东西必须单独工作;)
非常感谢您的帮助。
最佳答案
请参阅此处http://jsbin.com/wesucefofuyo/1/edit
var app = angular.module('app',[]);
app.service("tempService", ["$interval", function ($interval) {
//revealing module pattern
var m_temp = {
temp:0,
time:null
};
var requestTemp = function() {
m_temp.temp++;
m_temp.time = new Date();
};
var startTemp = function() {
$interval(requestTemp, 3000);
};
return {
startTemp :startTemp,
m_temp:m_temp
};
}]);
app.controller('fCtrl', function($scope,tempService){
$scope.temp = tempService;
$scope.temp.startTemp();
});
关于javascript - AngularJS 通过服务自动更新 Controller 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26157287/