我有以下html(样本)
<div ng-controller='ctrl-1'>
<form>
<input type='text' ng-model='name'/>
</form>
</div>
并且js文件为:
app.controller('ctrl-1',function($scope){
$scope.name = 'john';
});
app.controller('ctrl-2',function($scope){
/*
Here I want to change value of 'name' field which is in 'ctrl-1'
*/
});
如何在角度js中实现这一目标?
答案 0 :(得分:3)
虽然可以使用控制器继承或其他方法实现此目的,但最佳做法是将值保留在服务/工厂中:
app.service('MyService', function() {
this.name = 'John';
}
然后您可以通过将服务注入控制器来访问
app.controller('ctrl-1', function($scope, MyService) {
$scope.name = MyService.name;
}
app.controller('ctrl-2', function($scope, MyService) {
$scope.name = MyService.name;
}
编辑:如果你想更改一个控制器中的名称并让它反映另一个控制器中的更改,最好使用一个对象,因为你将在控制器中保存对该对象的引用
app.service('MyService', function() {
this.person = {};
this.person.name = 'John';
}
app.controller('ctrl-1', function($scope, MyService) {
$scope.person = MyService.person;
}
app.controller('ctrl-2', function($scope, MyService) {
$scope.person = MyService.person;
$scope.person.name = 'JFK';
//MyService.person will now also be updated in 'ctrl-1'
}