在AngularJS中保持不同控制器中的变量同步

时间:2015-07-09 15:26:09

标签: javascript angularjs controller

在控制器中,我正在运行一个间隔并在视图上显示变量value

$scope.value = 0;
var $higherScope = $scope;


interval = $interval(function () {

    $scope.value++; 

}, 1000);

现在我正在打开一个模态,我也想在这里显示这个变量:

$modal.open({
        templateUrl: 'modal.html',
        backdrop: true,
        windowClass: 'modal',
        controller: function ($scope, $modalInstance) {

            $scope.value = $higherScope.value;

        }
    });

当我这样做时,变量不会与上部var中的原始$scope同步显示,而只是在打开模态时变量的状态。

如何在模态中显示与上位控制器相同的内容,即实时计数?

1 个答案:

答案 0 :(得分:4)

一种方法是将您的价值放在注入两个控制器的服务中。

修改

使用$ interval(就像OP一样)在SomeController中更新AnotherController视图中显示的值的简化示例。

希望这更清楚: http://plnkr.co/edit/UqZ7tUHTPXnjeBP8j4qF?p=preview

<强> app.js

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

// For siplicity I put two controllers and a service/factory in this same file.
// IRL you everything should have its own file ;-)


app.factory('valueService', function($interval) {
  var service = {
    value: 0,
  };

  return service;
});



app.controller('SomeController', function($scope, $interval, valueService) {
  $scope.name = 'Some Controller';

  start();      // this line will execute when constructor initiates, starting the whole thing.

  function start() {
    $interval(function(){
      valueService.value++;   // this ctrl increments a value of the shared service (that the other controller uses to update its view)
    }, 1000);
  }
});


app.controller('AnotherController', function($scope, valueService) {
  $scope.name = 'Another Controller';
  $scope.valueService = valueService;
});

<强>的index.html

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>

  <script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.13/angular.js" data-semver="1.3.13"></script>
  <script src="app.js"></script>

</head>

<body>
  <div ng-controller="SomeController">
    <p>{{name}}</p>
  </div>
<hr/>

  <div ng-controller="AnotherController">
    <p>{{name}}</p>
    <p>{{valueService.value}}</p>
  </div>
</body>

</html>