2014-12-19 31 views
1

我在寻找一个更好的办法来做到以下几点:更新从多个控制器服务的变量

我有这个服务

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页面也会改变。但是这并没有发生。所以,我使用$手表:

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

然后,一切正常,因为我希望它。但我读过一些文章,据说不应该在控制器内部使用$ watch。

如何在没有$ watch的情况下实现此功能?

+0

其优良的使用$看你的控制器内。 – alsco77 2014-12-19 09:58:06

+0

@ alsco77,真的吗?这是好消息)[这里](http://www.benlesh.com/2013/08/angularjs-watch-digest-and-apply-oh-my.html)是我提到的链接,其中说“DON” T使用$ watch在控制器“ – Rodrigue 2014-12-19 10:01:00

+0

据我所见,他似乎只能看范围变量,而不是从外部服务 – alsco77 2014-12-19 10:06:00

回答

0

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

这里有一个例子:http://plnkr.co/edit/zNGnkfEsCIvLssCyHivg?p=preview

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" 
 
     } 
 
    }]);
<!DOCTYPE html> 
 
<html> 
 

 
    <head> 
 
    <script data-require="[email protected]" 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>

相关问题