如何避免在我的控制器中使用观察者?

时间:2014-06-10 01:52:46

标签: angularjs

好的,我知道将观察者放入控制器并不是一个好习惯,但在这种情况下,我怎样才能避免使用观察者?

ps:$ rootscope它不是一个选择吗?

这是代码:

plunker

编辑 - 这就是我所做的: plunker

这是js代码:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, mainService) {
  var flag = false;
  $scope.btn = function () {
    flag = !flag;
    mainService.setData(flag);  
  }
});

app.controller('DemoOneCtrl', function($scope, mainService) {
  $scope.name         = 'World';
  $scope.mainService  = mainService;
  $scope.show         = false;

  $scope.$watch('mainService.getData()', function (data) {
      $scope.show = data;  
  });
});

app.service('mainService', function () {
  var data = false;
  this.setData = function (str) {
    data = str; 
  };

  this.getData = function () {
    return data;  
  };
});

和html:

<div ng-controller="MainCtrl">
    <button ng-click="btn()">GO!</button>
</div>
<div ng-controller="DemoOneCtrl">
    <p ng-show="show">Hello World</p>
</div>

1 个答案:

答案 0 :(得分:1)

一种方法是将ng-show绑定到服务功能。

app.controller('MainCtrl', function($scope, mainService) {
  var flag = false;
  $scope.btn = function () {
    flag = !flag;
    mainService.setData(flag);  
  }
});

app.controller('DemoOneCtrl', function($scope, mainService) {
  $scope.name         = 'World';
  $scope.mainService  = mainService;
  $scope.show         = mainService.getData;

});

app.service('mainService', function () {
  var data = false;
  this.setData = function (str) {
    data = str; 
  };

  this.getData = function () {
    return data;  
  };
});

注意$scope.show如何设置为mainService.getData。现在,您可以将show()绑定到ng-show

<p ng-show="show()">Hello World</p>

不需要$watch

Demo