2014-10-17 43 views
1

我在角本的代碼結合的結構:Angular.js:雙向數據跨多個控制器

app.controller(AlphaCtrl, function(interstellarService){ 

    $scope.interstellarService = { 
    routeToEarth: interstellarService.get('routeToEarth'), 
    } 

}) 

app.controller(CentauriCtrl, function(interstellarService){ 

    $scope.interstellarService = { 
    routeToEarth: interstellarService.get('routeToEarth'), 
    } 
}) 

星際Service存儲在瀏覽器中存儲:

appServices.factory('interstellarService', function ($rootScope, $localStorage){ 
    return { 
     set: function(entidy, value) { 
      $localStorage[entidy] = value; 
     }, 
     get: function(entidy) { 
      if ($localStorage[entidy] !== undefined) { 
       return $localStorage[entidy]; 
      } else return false; 
     } 
    } 
}); 

現在,當我改變在AlphaCtrlrouteToEarth屬性通過setter方法我期望CentauriCtrl相應地更新,因爲數據綁定在每個控制器到服務,如:

AlphaCtrl < - 數據 - > interstellarService < - 數據 - > CentauriCtrl

這是行不通:我想用和共享存儲在routeToEarth在我半人馬座,HTML,例如價值

<li> 
    <a> 
    {{interstellarService.routeToearth}} && 'Timetravel' || 'Wormhole' }} 
    </a> 
</li> 

我在這裏錯過了什麼?

+0

你應該嘗試的工廠,而不是 – 2014-10-17 09:11:35

+0

好吧,我更新了我的代碼廠仍然沒有工作。 – nottinhill 2014-10-17 09:53:15

+0

你以前在工廠設置過嗎?此外,這個表達應該做什麼?你可以嘗試渲染{{interstellarService.routeToearth}}部分嗎? – tmaximini 2014-10-17 09:59:34

回答

3

您需要進行一些更改才能使其運行。

  1. 缺失報價爲AlphaCtrlCentauriCtrl
  2. 錯過注入$範圍同時爲AlphaCtrlCentauriCtrl控制器
  3. 控制器和不同,你提到它作爲appServices服務和app的控制器
  4. 服務模塊

Working Demo

腳本

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

appServices.factory('interstellarService', function ($rootScope, $localStorage) { 
    return { 
     set: function (entidy, value) { 
      $localStorage[entidy] = value; 
     }, 
     get: function (entidy) { 
      if ($localStorage[entidy] !== undefined) { 
       return $localStorage[entidy]; 
      } else return false; 
     } 
    } 
}); 

appServices.controller('AlphaCtrl', function (interstellarService, $scope) { 
    interstellarService.set('routeToEarth', 'Alpha'); 
    $scope.interstellarService = { 
     routeToEarth: interstellarService.get('routeToEarth'), 
    } 
    console.log('AlphaCtrl value::', $scope.interstellarService); 
}) 

appServices.controller('CentauriCtrl', function (interstellarService, $scope) { 
    interstellarService.set('routeToEarth', 'Centauri'); 
    $scope.interstellarService = { 
     routeToEarth: interstellarService.get('routeToEarth'), 
    } 
    console.log('CentauriCtrl value::', $scope.interstellarService); 
}) 

的Html

<div ng-controller="AlphaCtrl"> 
    {{interstellarService.routeToEarth}} 
</div> 
<div ng-controller="CentauriCtrl"> 
    {{interstellarService.routeToEarth}} 
</div> 
0

將這些放在我的CentauriCtrl終於顯示出地球的路線immeadiately,當我在AlphaCtrl改變它。

$rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){ 

     $scope.interstellarService = { 
      routeToEarth: interstellarService.get('routeToEarth'), 
     } 
    }); 

悼念這太問題:AngularJS Bootstraps Navbar