我正在使用服务在两个 Controller 之间传递变量。但我正在努力如何更改对象属性的值。我想在第一个 Controller 中更改此值并在第二个 Controller 中使用该新值。您可以在下面找到我的试用版。
可以找到 JSfiddle here
HTML 代码
<div ng-app="myApp">
<div ng-controller="myController">
<h3>{{objectValue.data}}</h3>
<button ng-click="changeObject()">Change the objectValue</button>
</div>
<div ng-controller="myController2">
<h2>{{ newValue.data}}</h2>
</div>
</div>
JS代码
var app = angular.module('myApp', []);
app.service('sharedProperties', function() {
var objectValue = {
data: 'default service value'
};
return {
getObject: function() {
return objectValue;
}
}
});
app.controller('myController', function($scope, sharedProperties) {
$scope.objectValue = sharedProperties.getObject();
var changeObject = function() {
sharedProperties.objectValue.data = "New value";
}
});
app.controller('myController2', function($scope, sharedProperties) {
$scope.newValue = sharedProperties.getObject();
});
最佳答案
在演示中的第一个 Controller 中,您仅将对象的一个属性分配给作用域变量...使其成为基元。基元没有继承,按值分配
如果您在每个作用域模型中维护对同一对象的引用,并且仅在 View 中显示它的属性,则通过对象继承来维护绑定(bind)。
演示服务中用于stringvalue
的原语永远不会有任何继承,因为它不是对象
使用
app.controller('myController1', function($scope, $timeout, sharedProperties) {
$scope.objectValue = sharedProperties.getObject();
});
并查看
{{objectValue.data}}
由于对象上有内部 Angular 监视,将为您提供 View 中的实时更新
关于javascript - Angular - 更改服务中的对象属性值并在另一个 Controller 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35564277/