angularjs服务混乱
下面的元素在我的mainController中
<img src="loader.gif" ng-hide="done_ajax"/>
我不能改变使用$ scope.done_ajax,因为我的ajax是在另一个控制器中完成的。 我如何在mainController和我的controller2之间进行通信?
app.service('finished_request', function(){
});
callAPI("getUser", {
            method: "GET"
        }).done(function (resp) {
            $scope.$apply(function () {
            });
});
如果你想在两个控制器之间共享数据,你可以使用服务 。 服务是单身,所以你可以轻松地分享你的数据。
  但是,您希望在更改数据时进行通知,因此要使用$broadcast()和$on()方法来实现此目的。 
$broadcast :向下调度事件到所有子范围   由于您的范围之间没有父子关系,如果您的控制器处于同一级别,则可以将$rootScope注入控制器并将该事件广播到所有子范围。 
编辑
有服务和广播参数的例子。
所以你可以这样做:
调节器
(function(){
function Controller($scope, $rootScope, Service) {
  $scope.data = 1;
  $scope.set = function(n){
    $scope.data = n;
    Service.set($scope.data);
    $rootScope.$broadcast('set', $scope.data);
  }
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
(function(){
function Controller($scope, Service) {
  $scope.$on('set', function(e, data){
    $scope.data2 = Service.get();
    $scope.data3 = data;
  });
}
angular
.module('app')
.controller('ctrl2', Controller);
})();
服务
(function(){
  function Service(){
    var data;
    function get(){
      return data;
    }
    function set(value){
      data = value;
    }
    return {
      get: get,
      set: set
    };
  }
  angular
    .module('app')
    .factory('Service', Service);
})();
HTML
  <body ng-app='app'>
    <h3>Controller 1</h3>
    <div ng-controller="ctrl">
      <button ng-click="set(data)">change</button>
      <input type="text" ng-model="data">
    </div>
    <h3>Controller 2</h3>
    <div ng-controller="ctrl2">
      <p>Data from controller 1 : {{data2}}</p>
      <p>Data from controller 1 without service : {{data3}}</p>
    </div>
  </body>
现在,您将能够在不同的控制器之间进行通信,并通过使用服务来检索数据。
你可以看到Plunker
只需使用服务单例
调节器
(function(){
function Controller($scope, Service) {
  $scope.data = 1;
  $scope.set = function(n){
    Service.set(n)
  }
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
(function(){
function Controller($scope, Service) {
  //Retrieve service instance
  $scope.data_service = Service;
}
angular
.module('app')
.controller('ctrl2', Controller);
})();
HTML
  <body ng-app='app'>
    <h3>Controller 1</h3>
    <div ng-controller="ctrl">
      <button ng-click="set(data)">change</button>
      <input type="text" ng-model="data">
    </div>
    <h3>Controller 2</h3>
    <div ng-controller="ctrl2">
      <p>Data from controller 1 : {{data_service.get()}}</p>
    </div>
  </body>
在这里,我们只是分享我们服务的实例。
你可以看到带服务的Plunker
链接地址: http://www.djcxy.com/p/77567.html