更改控制器中的值组件内容

时间:2015-01-08 21:45:56

标签: angularjs

我有一个字符串,我想从多个控制器调用和操作。我读了different types of components并认为值组件是合适的,因为它只需要存储一个字符串而不是逻辑。

使用以下代码,我可以调用值组件,但是如何操作它以便在所有控制器中更新它:

angular.module('myApp', [])

.value('alertInfo', undefined)

.controller('Controller1', [
  'alertInfo',
  function(alertInfo) {
    alertInfo = "Some value from Controller1"
  }
])

.controller('Controller2', [
  'alertInfo',
  function(alertInfo) {
    alertInfo = "Some value from Controller2"
  }
]);

1 个答案:

答案 0 :(得分:2)

你不能,不是这样。角度服务食谱是单身人士。所以一旦你设置它就无法真正更新它。相反,您可能希望使用对象引用并更新属性。

即示例: -

 .value('alertInfo', {}) //Set it as an object, or object with a property with default value

.controller('Controller1', ['alertInfo', function(alertInfo) {
    alertInfo.value = "Some value from Controller1"; //<-- Update a property on the value object.
  }
])

.controller('Controller2', ['alertInfo', function(alertInfo) {
    alertInfo.value = "Some value from Controller2"
  }
]);

但理想情况下,如果您计划对数据执行更合适的操作,则可以创建服务。

angular.module('myApp', [])

.value('alertInfo', {})

.controller('Controller1', [
  'alertInfo',
  function(alertInfo) {
    alertInfo.value = "Some value from Controller1";
    this.getValue = function() {
      return alertInfo.value;
    }
    this.update = function() {
      alertInfo.value = "Updated from Controller1";
    }
  }
])

.controller('Controller2', [
  'alertInfo',
  function(alertInfo) {
    alertInfo.value = "Some value from Controller2";
    this.getValue = function() {
      return alertInfo.value;
    }
    this.update = function() {
      alertInfo.value = "Updated from Controller2";
    }
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="Controller1 as ctrl1">{{ctrl1.getValue()}}
    <button ng-click="ctrl1.update()">Update</button>
  </div>
  <div ng-controller="Controller2 as ctrl2">{{ctrl2.getValue()}}
    <button ng-click="ctrl2.update()">Update</button>
  </div>

</div>