Angularjs绑定来自服务的值



我希望在一个或多个控制器之间共享服务值(以下示例中只有一个,但这不是重点(。

问题a是服务中的值未绑定并显示在视图中。

代码(源自angularjs基本服务示例(为:

(function(angular) {
'use strict';
angular.
module('myServiceModule', []).
controller('MyController', ['$scope', 'notify','$log', function($scope, notify, $log) {
$scope.callNotify = function(msg) {
notify.push(msg);
};
$scope.clickCount = notify.clickCount();
$log.debug("Click count is now", $scope.clickCount);
}]).
factory('notify', ['$window','$log', function(win,$log) {
var msgs = [];
var clickCounter = 0;
return {
clickCount: function() {
clickCounter = msgs.length;
$log.debug("You are clicking, click count is now", clickCounter);
return clickCounter;
},
push: function(msg) {
msgs.push(msg);
clickCounter = msgs.length;
$log.debug("Counter is", clickCounter);
if (msgs.length === 3) {
win.alert(msgs.join('n'));
msgs = [];
}
}
}
}]);

我希望计数器显示在页面上:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-services-usage-production</title>

<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<script src="script.js"></script>

</head>
<body ng-app="myServiceModule">
<div id="simple" ng-controller="MyController as self">
<p>Let's try this simple notify service, injected into the controller...</p>
<input ng-init="message='test'" ng-model="message" >
<button ng-click="callNotify(message);">NOTIFY</button>
<p>(you have to click {{3-self.clickCount}} times more to see an alert)</p>
</div>
<div>You have clicked {{clickCount}} times</div>
</body>
</html>

在plunker 上看到它的动作

更新:根据@SehaxX 的建议,更正了html和服务代码的琐碎错误

首先,您的HTML是错误的。您的最后一个div不在Controller的div中,并且您不需要self。

<body ng-app="myServiceModule">
<div id="simple" ng-controller="MyController">
<p>Let's try this simple notify service, injected into the controller...</p>
<input ng-init="message='test'" ng-model="message" >
<button ng-click="callNotify(message);">NOTIFY</button>
<p>(you have to click {{3-self.clickCount}} times more to see an alert)</p>
<div>You have clicked {{clickCount}} times</div>
</div>    
</body>

同样在您的服务中,您错过了退货:

clickCount: function() {
clickCounter = msgs.length;
$log.debug("You are clicking, click count is now", clickCounter);
return clickCounter;
},

在你的控制器中,你只调用了一次notice.colickCount((,所以你需要将其添加到方法中:

$scope.callNotify = function(msg) {
notify.push(msg);
$scope.clickCount = notify.clickCount();
$log.debug("Click count is now", $scope.clickCount);
};

如果你愿意的话,这里还有一支带"Controller as self"的工作代码笔。但在控制器中,您必须使用this而不是$scope。

干杯,

最新更新