从服务到控制器传递切换布尔值

时间:2016-03-08 23:48:21

标签: angularjs service controller boolean toggle

我想根据我的服务中更改的布尔值显示/隐藏元素。我希望更改此布尔值在我的服务中发生,因此多个控制器可以访问true或false值,但是我无法将此值返回到一个或多个控制器。目前我只能传递一个为false的值,尽管该值确实表明它在我的服务中正在发生变化。这是我的控制器的一个例子......

angular.module('myApp')
   .service('ThisService', function(){
       function toggleDisplay(){
          return displayElement = !displayElement;
       }
   });

   .controller('ThisCtrl', function (thisService, $scope) {

        function init(){
            $scope.displayElement = ThisService.toggleDisplay();
        }

        $scope.toggleElement = function(){
            $scope.displayElement = ThisService.toggleDisplay();
        }

        init();
    });

我的HTML ...

<div ng-show="displayElement">Show hide me</div>
<button ng-click='toggleElement()'></button>

请告诉我如何正确地将真/假值返回给我的控制器?

1 个答案:

答案 0 :(得分:1)

您可以使用值,然后在服务中切换。但是,您的服务定义无效,您的模块链中间有一个分号,并且您使用名称&#34; ThisService&#34;定义您的服务,但是您尝试在控制器中引用它as&#34; thisService&#34; (它区分大小写)。

JS:

angular.module("myApp", [])
    .value("DisplayElement", { value: true })
    .service("ThisService", function(DisplayElement) {
        this.toggleDisplay = function() {
          return DisplayElement.value = !DisplayElement.value;
        }
    })
    .controller("ThisCtrl", function(ThisService, $scope) {
        function init() {
            $scope.displayElement = ThisService.toggleDisplay();
        }

        $scope.toggleElement = function() {
            $scope.displayElement = ThisService.toggleDisplay();
        }

        init();
    });

HTML:

<div ng-app="myApp">
  <div ng-controller="ThisCtrl">
    <div ng-show="displayElement">Show hide me</div>
    <button ng-click="toggleElement()">Toggle Display</button>
  </div>
</div>

jsFiddle

您甚至可以取消服务,只需直接在控制器中访问该值(您必须先将其注入)。