如何在AngularJS中更改不同控制器的表单值

时间:2016-09-23 12:49:09

标签: angularjs angularjs-scope angular-controller

我有以下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中实现这一目标?

1 个答案:

答案 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'
}