javascript - 如何获取表单的 Controller

标签 javascript html angularjs

假设我有几个表单,每个表单都有自己的 Controller ,如下所示

 <div ng-controller="MyController1 as ctrl">
    <label>Some label </label>
</div>

<div ng-controller="MyController2 as ctrl">
    <label>Some label </label>
</div>

我有一个全局 Controller ,它获取有关表单名称的信息。现在我想找到每个表单的 Controller 。例如,如果在我的全局 Controller 函数中,我获取了第一个表单的名称,我如何才能知道它的 Controller 是MyController1?这可能吗?

最佳答案

可以从另一个 Controller 调用一个 Controller 。但是,我相信您想要解决的问题在其他地方:您的应用程序的架构。

理想情况下,您的应用应该对状态的变化做出“ react ”。状态应该保存在一个地方(也称为“单一事实来源”),即。一项服务。然后,您可以与所需数量的 Controller 共享该服务状态。

您可以直接从 Controller 更新服务状态,也可以通过调用服务本身的方法来更新服务状态。

看下面的例子。我希望这能带来一些启发。

干杯!

angular.module('app', [])
.service('MyService', function(){
  var self = this;
  self.state = {
    name: 'John'
  };
  
  self.changeNameFromService = function() {
    self.state.name = 'Peter';
  }
})
.controller('Ctrl1', function($scope, MyService){
  $scope.state = MyService.state;
  
  $scope.changeName = function(){
    // update the state of the scope, which is shared with other controllers by storing the state in a service
    $scope.state.name = 'Mary';
  }
})
.controller('Ctrl2', function($scope, MyService){
  $scope.state = MyService.state;
  
  // call a method defined in service
  $scope.changeName = MyService.changeNameFromService;
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="Ctrl1">
    Ctrl1: {{state.name}}
    <button ng-click="changeName()">Change name!</button>
  </div>
  
  <div ng-controller="Ctrl2">
    Ctrl2: {{state.name}}
    <button ng-click="changeName()">Change name from service!</button>
  </div>
</div>

关于javascript - 如何获取表单的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41985424/

相关文章:

javascript - jquery 添加选中的单选父 div 类

javascript - AngularJS ng-绑定(bind)到动态变量名称

javascript - 查找分解的 unicode 字符以替换为预组合的等价物

javascript - 如何单击文本本身将文本更改为输入字段

javascript - Dojo 编辑器中的 Css

html - `<select>` 标签内的输入文本字段

CSS 响应能力推荐?

c# - 在 Kendo UI 网格中控制组顺序

javascript - LocalStorage 设置数组内的对象 Ionic List

angularjs - 在 ng Select 中设置默认值