从控制器看着的服务的价值 [英] Watching a values in a service from a controller

查看:112
本文介绍了从控制器看着的服务的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个服务来隔离业务逻辑和我在需要该信息的控制器注入它。我想最终做的是有控制器能够观看在服务中的值,这样我就不用做广播/在通知或传递解决方案将所有的控制器被变更通知中的数据的复杂的消息该服务。

I have created a service to isolate the business logic and am injecting it in to the controllers that need the information. What I want to ultimately do is have the controllers be able to watch the values in the service so that I don't have to do broadcast/on notification or a complex message passing solution to have all controllers be notified of changes to the data in the service.

我创建了一个plnkr证明什么,我试图做的基本思想。

I've created a plnkr demonstrating the basic idea of what I'm trying to do.

<一个href=\"http://plnkr.co/edit/oL6AhHq2BBeGCLhAHX0K?p=$p$pview\">http://plnkr.co/edit/oL6AhHq2BBeGCLhAHX0K?p=$p$pview

是否有可能有一个控制器观看服务的价值?

Is it possible to have a controller watch the values of a service?

推荐答案

您已经在这样做的权利。即推动服务为一体的范围变量,然后观察服务为范围变量的一部分。

You were already doing it right. i.e pushing the service into a scope variable and then observing the service as part of the scope variable.

下面是你的工作液:

<一个href=\"http://plnkr.co/edit/SgA0ztPVPxTkA0wfS1HU?p=$p$pview\">http://plnkr.co/edit/SgA0ztPVPxTkA0wfS1HU?p=$p$pview

HTML

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <script>document.write('<base href="' + document.location + '" />');</script>
  <link rel="stylesheet" href="style.css">
  <script src="http://code.angularjs.org/1.1.3/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
  <button ng-click="start()">Start Count</button>
  <button ng-click="stop()">Stop Count</button>
  ControllerData: {{controllerData}}
</body>
</html>

使用Javascript:

Javascript :

var app = angular.module('plunker', []);

app.service('myService', function($rootScope) {
  var data = 0;
  var id = 0;

  var increment = function() {
    data = data + 1;
    $rootScope.$apply();
    console.log("Incrementing data", data);
  };

  this.start = function() {
    id = setInterval(increment, 500) ;

  };

  this.stop = function() {
    clearInterval(id);
  };

  this.getData = function() { return data; };

}).controller('MainCtrl', function($scope, myService) {
  $scope.service = myService;
  $scope.controllerData = 0;

  $scope.start = function() {
    myService.start();
  };

  $scope.stop = function() {
    myService.stop();
  };

  $scope.$watch('service.getData()', function(newVal) {

    console.log("New Data", newVal);
    $scope.controllerData = newVal;
  });
});

下面是一些你错过的事情:

Here are some of the things you missed :


  1. 在$范围。$观察变量的顺序是错误的。它(的newval,OLDVAL),而不是相反。

  2. 既然你在使用setInterval,这是一个异步操作,则必须让角度知道,事情发生了变化工作。这就是为什么你需要$ rootScope。$适用。

  3. 您不能$观看的功能,但你可以看一下函数返回的。

这篇关于从控制器看着的服务的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆