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

How to change form value from different controller in AngularJS

我关注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'
    */
});

如何在 angular js 中实现?

虽然可以使用控制器继承或其他方式实现此目的,但最佳做法是将值保存在 service/factory:

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