我正在尝试使用服务将信息从一个控制器传递到另一个控制器。
它工作正常,但在下面的片段/小提琴中,我必须:
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>
答案 0 :(得分:2)
解决方案是使用您的factory
返回一个对象(包含您的属性)。在您的控制器中,您将能够使用此对象作为参考,它将自动更新:
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>