Angular.js:跨多个控制器的双向数据绑定

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

本文关键字:数据绑定 控制器 js Angular      更新时间:2023-09-26

我在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属性时,我希望半人马座Ctrl相应地更新,因为数据在每个控制器上都绑定到服务,如:

AlphaCtrl<--data-->星间服务<--数据-->半人马座Ctrl

这是不起作用的:我想在我的半人马座HTML中使用并共享routeToEarth中存储的值,例如

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

我在这里错过了什么?

您需要进行某些更改才能运行它。

  1. 缺少AlphaCtrlCentauriCtrl的引号
  2. 错过为AlphaCtrlCentauriCtrl控制器注入$scope
  3. 控制器和服务模块是不同的,您提到它是appServices用于服务,app用于控制器

工作演示

脚本

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引导Navbar