从多个控制器更新服务中的变量

时间:2014-12-19 09:49:32

标签: javascript angularjs

我正在寻找更好的方法来执行以下操作:

我有服务

dashboardApp.service('MessagesService', function () {
   var message = "";

    this.update = function (new_message) {
        message = new_message;
    };

    this.get = function () {
        return message;
    }
});

让我们说我有控制器

dashboardApp.controller('GroupPageController', function($scope, MessagesController){
    $scope.message = MessagesController.get();
})

$ scope.message变量在我的HTML页面中:

<h3 ng-bind="message"></h3>

让我们说我有第二个控制器

dashboardApp.controller('ChangeController', function($scope, MessagesController, $http){

    $scope.sendEmail = function () {

        $http({
            method: "post",
            url: "/enterprises/vouchers/_send",
            data: {
                group_id: group_id,
                group_student_ids: group_student_ids
            }
        }).success(function (response) {
            MessagesService.update(response.message);
        }).error(function () {
            console.log("failed")
        });

    }

})

所以这里,当点击某个按钮时,此函数从Web API获取数据并更新服务中的变量。然后,我希望第一个控制器中的$ scope.message变量也会更新,以便HTML页面也会发生变化。但这不会发生。所以,我使用$ watch:

$scope.$watch(function () {
    return MessagesService.get();
}, function (newValue, oldValue) {
    if (newValue !== oldValue) {
        $scope.message = MessagesService.get();
    }
});

然后,一切都按照我的意愿运作。但我读了一些文章,据说$ watch不应该在控制器内使用。

如果没有$ watch,我怎样才能实现此功能?

1 个答案:

答案 0 :(得分:0)

您可以在没有观察者的情况下在控制器之间共享数据。您只需要在作用域上声明服务,然后就可以使用作用域更新服务的属性。

以下是一个示例:http://plnkr.co/edit/zNGnkfEsCIvLssCyHivg?p=preview

&#13;
&#13;
    var app = angular.module("myApp", []);
    
    app.controller('myCtrl', ['$scope', 'sharedDataService', function($scope, sharedDataService){
    
      $scope.sharedDataService = sharedDataService;
      
    }]); 
    
    app.controller('mySecondCtrl', ['$scope', 'sharedDataService', function($scope, sharedDataService){
    
      $scope.sharedDataService = sharedDataService;
      
    }]); 
    
    app.service('sharedDataService', [function(){
      return {
        someData: "Share Me"
      }
    }]);
&#13;
<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@1.3.6" data-semver="1.3.6" src="https://code.angularjs.org/1.3.6/angular.js"></script>
    <link href="style.css" rel="stylesheet" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp">
  
    <div ng-controller="myCtrl"> 
      Controller one:
      
      <input ng-model="sharedDataService.someData">
      
    </div>  
    
    <br>
    
    <div ng-controller="mySecondCtrl"> 
      Controller two:
      <input ng-model="sharedDataService.someData">
      
    </div>  
    
  </body>

</html>
&#13;
&#13;
&#13;

相关问题