Bạn đã làm đúng. tức là đẩy dịch vụ vào một biến phạm vi và sau đó quan sát dịch vụ như một phần của biến phạm vi.
Dưới đây là giải pháp làm việc cho bạn:
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:
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;
});
});
Dưới đây là một số trong những điều bạn bỏ lỡ:
- Thứ tự các biến trong phạm vi $. $ Xem là sai. Của nó (newVal, oldVal) và không phải là cách khác xung quanh.
- Vì bạn đang làm việc với setInterval, một hoạt động không đồng bộ, bạn sẽ phải cho phép góc nhìn biết mọi thứ đã thay đổi. Đó là lý do tại sao bạn cần $ rootScope. $ Áp dụng.
- Bạn không thể $ xem một hàm, nhưng bạn có thể xem hàm trả về của hàm.
Lưu ý của tôi là vì trình ngắt thư bị mất, do đó, mã sẽ hiển thị câu hỏi này (và trả lời) vô ích. :(Đặt mã ở đây và tôi sẽ +1 câu hỏi của bạn –