AngularJS服务绑定值

时间:2018-11-12 15:18:25

标签: angularjs angularjs-scope

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

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

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

1 个答案:

答案 0 :(得分:0)

首先,您的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;
          },

在您的控制器中,您只需调用一次notify.clickCount(),因此您需要将其添加到方法中:

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

如果需要的话,这里的code pen也可以使用“控制器作为自我”。但是在控制器中,您必须使用它而不是$ scope。

干杯