从控制器观察服务中的值 [英] Watching a values in a service from a controller
问题描述
我创建了一个服务来隔离业务逻辑,并将其注入到需要信息的控制器中.我最终想要做的是让控制器能够查看服务中的值,这样我就不必进行广播/通知或复杂的消息传递解决方案来通知所有控制器中的数据更改服务.
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.
http://plnkr.co/edit/oL6AhHq2BBeGCLhAHX0K?p=preview
是否可以让控制器监视服务的值?
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.
这是适合您的工作解决方案:
Here is the working solution for you :
http://plnkr.co/edit/SgA0ztPVPxTkA0wfS1HU?p=preview
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 :
- $scope.$watch 中变量的顺序是错误的.它的 (newVal,oldVal) 而不是相反.
- 由于您使用的是 setInterval ,这是一个异步操作,因此您必须让 angular 知道事情发生了变化.这就是为什么你需要 $rootScope.$apply.
- 你不能 $watch 一个函数,但你可以观察函数返回的内容.
这篇关于从控制器观察服务中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!