首页 > angularjs中多个controller如何监听服务变化

angularjs中多个controller如何监听服务变化

RT
我注册了一个服务,并创建了多个controller,这样多个controller就能共享定义的服务了。
但是服务变更的时候,我想触发controller的事件,如何做到呢?$watch好像不行!

app.controller('SelectController', function($scope, Service) {
  $scope.service = Service;

  // 这个是可以检测到的
  $scope.$watch('service', function() {
    alert('aaa');
  });

  // 触发改变的事件
  $scope.generate = function() {
    $scope.Service = {
      id: '234'
    };
  }
});

app.controller('GraphController', function($scope, Service) {
  $scope.service = Service;

  // 这个是不能检测到的, 可以我想要这个也触发(当其他controller的service改变的时候)
  $scope.$watch('service', function() {
    alert('456');
  });
});

你的代码里面很多地方是有问题的

$scope.generate = function() {
    $scope.Service = {
      id: '234'
    };
  }

这里用 $scope.Service 其实是在这个 controller 里面又加了一个 $scope.Service 这两个变量,它的 scope 是在 selectController 里面,是不会影响到 graphController 里面的,如下图:

代码可以改成这样

$scope.generate = function() {
    $scope.service.name = "jimmy";
  };

然后就是 $watch 这里的问题了,$watch 的值只是第一次传入的值,文档里面关于 $watch 是这样介绍的:$watch(watchFn, watchAction, deepWatch),所以如果需要让它始终监视 service.id 的变化,则将 deepWatch 设置为 true:

$scope.$watch('service', function(newVal, oldVal) {
    if (newVal !== oldVal) {
      alert('SelectController value changed!');
    }
  }, true);

最后我把代码和起来了,大概就是这样,html:

<!DOCTYPE html>
<html>
<head>
  <title>TEST</title>
 </head>
<body>

<div ng-app="myApp">
    <div ng-controller="SelectController">
      <input type="text" ng-model="service.id">
      <h1>{{service.id}}</h1>
      <button ng-click="generate()">Generate</button>
    </div>

    <div ng-controller="GraphController">
      <input type="text" ng-model="service.id">
      <h1>{{service.id}}</h1>
    </div>
  </div>

  <script type="text/javascript" src="angular.min.js"></script>
  <script type="text/javascript" src="main.js"></script>
</body>
</html>

main.js:

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

app.factory('Service', function () {
  return {id: "345", name: "teddy"};
});

app.controller('SelectController', function($scope, Service) {
  $scope.service = Service;

  $scope.$watch('service', function(newVal, oldVal) {
    if (newVal !== oldVal) {
      alert('SelectController value changed!');
    }
  }, true);


  $scope.generate = function() {
    $scope.service.name = "jimmy";
  };
});

app.controller('GraphController', function($scope, Service) {
  $scope.service = Service;
  $scope.$watch('service', function(newVal, oldVal) {
    if (newVal !== oldVal) {
      alert("GraphController changed");
    }
  }, true);
});
【热门文章】
【热门文章】