javascript - 触发属性作为 angularjs 指令的函数

标签 javascript angularjs angularjs-directive

我将此 html 模板放入 fileA.directive.html 中:

<md-button ng-click="resetForm()" class="btn btn-primary">Reset form</md-button>
<user-form reset-user-fn=""></user-form>

进入我的fileA.directive.js:

app.directive("shopAppFormCustomer", function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "fileA.directive.html",
      scope: {},
      controller: [
        "$scope",
        function($scope) {
          $scope.resetForm = function () {
             // want to call reset-user-fn here
          }
        }
      ]
    };
  })

在我的fileB.directive.js中,我有userForm指令

app.directive("userForm", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "fileB.directive.html",
    scope: {resetUserFn: "=" },
    controller: [
       "$scope",
        function ($scope) {
          $scope.resetUserFn = function () {
             // reset goes here
          }
        }
    ]
  }

这是我的问题:

如何将 fileB.directive.js 中的属性 resetUserFn 触发到 fileA.directive.js 中?

请提供任何来源或文档。

注意:如果可能的话,我不会使用自定义事件。

最佳答案

所以你想从父指令触发子指令的某些方法。不幸的是,AngularJS 没有对此类问题的原生支持。以下是一些供您考虑的解​​决方法

  1. 使用内置事件调度程序,here is一个很好的解释。
  2. 基于组件的 $onChanges 方法,described here
  3. 每个 Angular 服务都是一个单例,因此您可以创建 service ,用于亲子沟通。

每种方法都非常丑陋!

  1. 事件调度程序 - 太多的事件可能会显着降低应用程序的速度。您最终可能会遇到数百个事件,这确实很难维护。
  2. $onChanges - 代码看起来很难看,难以维护。
  3. 每个案例都需要一个新的服务,这很难维护。

我认为有一些原因导致它不受 native 支持。如果您有两个或更多<user-form reset-user-fn=""></user-form>怎么办? shopAppFormCustomer下的指令家长指令?您想调用 resetUserFn某一特定的userForm指令,如何区分userForm来自另一个userForm

Angualar 2 及更高版本以某种方式支持这一点,但该解决方案也不完美。因此,您只需从上面选择一种对您来说不那么痛苦的解决方案并进行处理即可。

关于javascript - 触发属性作为 angularjs 指令的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53910880/

相关文章:

Javascript - 在一行中评估多个正则表达式

javascript - Webkit JavaScript 引用

javascript - 在 Angular 中禁用动态生成字段的输入

javascript - 带有提交输入的 AngularJS ajax 表单提交

javascript 使用 echo 监听多个套接字 channel

javascript - 如果数组中已存在 id 则隐藏特定的 ng-option

javascript - 将新对象添加到现有的 json

angularjs - 如何在弹出窗口中渲染 Angular 指令,并允许其与主窗口进行通信?

css - 在绘制的 Canvas 元素上应用 CSS

javascript - JS 中 Blob 对象和 File 对象有什么区别?