簡體   English   中英

Angular.js:跨多個控制器的雙向數據綁定

[英]Angular.js: Two-Way data binding across multiple controllers

我在Angular中有這個代碼結構:

app.controller(AlphaCtrl, function(interstellarService){

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

})

app.controller(CentauriCtrl, function(interstellarService){

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

星際服務存儲在瀏覽器存儲中:

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;
        }
    }
});

現在,當我通過setter方法更改了AlphaCtrlrouteToEarth屬性時,我希望CentauriCtrl能夠相應地更新,因為數據在每個控制器上綁定到服務,如:

AlphaCtrl < - data - > interstellarService < - data - > CentauriCtrl

這是行不通的:我想在Centauri-HTML中使用和共享存儲在routeToEarth中的值,例如

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

我在這里錯過了什么?

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

  1. 缺少AlphaCtrlCentauriCtrl的報價
  2. 錯過了為AlphaCtrlCentauriCtrl控制器注入$ scope
  3. 控制器和服務模塊不同,您將其稱為appServices for service和app for controller

工作演示

腳本

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>

當我在AlphaCtrl更改它時,將它放入我的CentauriCtrl終於顯示了通往地球的路線。

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

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

向此SO問題致敬: AngularJS Bootstraps Navbar

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM