javascript - AngularJS 通过服务自动更新 Controller 数据

标签 javascript angularjs model-view-controller angularjs-scope

目前我在 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/

相关文章:

javascript - JavaScript 中的 ActiveXObject 问题

javascript - 何时在 React 中使用基于类的组件

javascript - 运行时 react 故事书空白页

javascript - 当元素到达视口(viewport)顶部时将数据类型值设置为元素

javascript - 从字符串中替换所有出现的 html 标记和特殊 unicode 字符

python - 带有对象的 MVC 游戏设计

asp.net-mvc - 如何在 MVC 中制作短 URL?

javascript - 使用angularjs将json对象传递给python

css - 解析背景颜色值时出错 - angularjs

javascript - 从 via 更改数据似乎正在修改 localStorage 对象