javascript - AngularJS Controller 在指令中具有多个覆盖 Controller 方法的实例

标签 javascript angularjs

我有一个由指令组成的表单。该表单的两个部分在输入字段、选择和复选框中是相同的。我使用隔离范围和controllerAs语法(bindToController=true)创建了一个指令,其中 Controller 有一个从复选框上的ngChange触发的方法。我的问题是,我在 Controller 中分配“this”的 Controller 别名被触发两次,每个指令一次。第二次通过该 Controller 别名(在我的示例中为“ctrlVm”)将被第二个作用域覆盖。

重复此问题的更简单的指令和 Controller 是:

function myDirective() {
  var directive = {
    restrict: 'AE',
        priority: 100,
        require: 'ngModel',
    scope: {
      boundObject: '=boundObj',
      myArray: '='
    },
    templateUrl: 'myTemplate.html',
    controller: controller,
    controllerAs: 'ctrlVm',
    bindToController: true
  };
  return directive;

  function controller() {
    ctrlVm = this;
    ctrlVm.runTest = runTest;

    function runTest() {
      ctrlVm.myArray.push(ctrlVm.boundObject.first);
    }
  }
}

包含上述代码和 html 的完整演示可以在以下位置找到:

http://plnkr.co/edit/TdZgadsmVQiZhkQQYly1?p=preview

我基本上调用该指令两次,并期望它们产生“一”或“二”,具体取决于您单击的框。但如您所见,第一个 Controller 被第二个 Controller “覆盖”并且无论您选中哪个框,它都会触发第二个指令的函数,并向数组添加“two”,无论您单击哪个框。

我已经进行了一整天的详尽搜索,一路上学习了一些其他东西,但没有找到超过几个与这个问题相关的引用文献,而这两个引用文献似乎都意味着需要两个具有不同controllerAs的不同指令别名或接受 Controller 名称变量名的指令。这两个解决方案似乎都需要两个不同的 View ,因为我的 View 包括使用controllerAs别名(现在这对于两个指令来说是不同的)。

那么有没有办法做到这一点,重用 Controller 并使用controllerAs语法,并为两个指令单独存在示例runTest()函数?感谢您的帮助。

最佳答案

在指令的 Controller 中,您没有声明变量 ctrlVm。

所以改变:

  function controller() {
    ctrlVm = this;
    ctrlVm.runTest = runTest;

    function runTest() {
      ctrlVm.myArray.push(ctrlVm.boundObject.first);
    }
  }

致:

  function controller() {
    var ctrlVm = this;
    ctrlVm.runTest = runTest;

    function runTest() {
      ctrlVm.myArray.push(ctrlVm.boundObject.first);
    }
  }

http://plnkr.co/edit/Qab1lpgbrK8ZRLZiRdaQ?p=preview

关于javascript - AngularJS Controller 在指令中具有多个覆盖 Controller 方法的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34322510/

相关文章:

javascript - 用对象数据源填充选择

javascript - 如何在 Redux 中只更新 reducer 的一个值?

javascript - Protractor by.repeater 找不到任何东西

javascript - 为什么在 Angular 中使用 $http 而不是 jquery 的 ajax?

javascript - 单击功能后隐藏 jquery 菜单

引导模式弹出窗口内的 angularjs 表单

AngularJS 1.7.9 : how to debug "Possibly unhandled rejection: {}"?

javascript - Angular JS 应用程序无法通过 Wcf 服务从 Sql 数据库检索数据

javascript - Youtube API 未在 Firefox 中加载

javascript - 在javascript中从json中提取值