更改时在多个控制器上自动刷新服务值

时间:2017-05-02 12:03:39

标签: angularjs angular-services

我正在尝试使用服务将信息从一个控制器传递到另一个控制器。

它工作正常,但在下面的片段/小提琴中,我必须:

  • 输入中的类型值
  • 点击FirstController
  • 中的“设置值”按钮
  • 点击SecondController
  • 中的“获取价值”按钮
  • 现在显示该值

我希望更新后的值自动显示在SecondController 中。

angular.module('app', []);
angular.module('app').factory('StoreService', function () {
    var storedObject;
    return {
        set: function (o) {
            this.storedObject = o;
        },
        get: function () {
            return this.storedObject;
        }
    };
});

angular.module('app').controller('FirstController', function ($scope, StoreService) {
    $scope.setValue = function (value) {
        StoreService.set(value);
    };
});

angular.module('app').controller('SecondController', function ($scope, StoreService) {
    $scope.getValue = function () {
        $scope.value = StoreService.get();
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
    <div ng-controller="FirstController">
        <fieldset>
            <legend>FirstController:</legend>
            <input type="text" ng-model="value" />
            <button ng-click="setValue(value)">Set value</button>
        </fieldset>
    </div>
    <div ng-controller="SecondController">
        <fieldset>
            <legend>SecondController:</legend>
            <button ng-click="getValue()">Get value</button>
            Value: {{value}}
        </fieldset>
    </div>
</div>

Fiddle

1 个答案:

答案 0 :(得分:2)

解决方案是使用您的factory返回一个对象(包含您的属性)。在您的控制器中,您将能够使用此对象作为参考,它将自动更新:

Forked your Fiddle here

angular.module('app', []);
angular.module('app').factory('StoreService', function() {
  return {
    storedObject: ''
  };
});

angular.module('app').controller('FirstController', function($scope, StoreService) {
  $scope.value = StoreService;

});

angular.module('app').controller('SecondController', function($scope, StoreService) {
  $scope.value = StoreService;

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="FirstController">
    <fieldset>
      <legend>FirstController:</legend>
      <input type="text" ng-model="value.storedObject" />
      <button ng-click="setValue(value)">Set value</button>
    </fieldset>
  </div>
  <div ng-controller="SecondController">
    <fieldset>
      <legend>SecondController:</legend>
      Value: {{value.storedObject}}
    </fieldset>
  </div>
</div>