Angularjs 来自服务的绑定值

Angularjs binding value from service

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

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

代码(源自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

上查看实际效果

更新:更正了微不足道的错误 html 和@SehaxX 建议的服务代码

首先你的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>

在你的服务中你也失踪了return:

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

并且在你的控制器中你只调用了一次 notify.clickCount() 所以你需要将它添加到方法中:

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

如果需要,这里还有一个工作 code pen 和 "Controller as self"。但是在控制器中你必须使用它而不是 $scope.

干杯,