2014-12-19 32 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>

相關問題