本文介绍了触发属性作为 angularjs 指令的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this html template into 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 指令

Into my fileB.directive.js, I have the userForm directive

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

这是我的问题:

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

How can I trigger the attribute resetUserFn into my fileB.directive.js into my fileA.directive.js?

请提供任何来源或文档.

Any source or documentation please.

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

Note: I won't to use custom event if it's possible.

推荐答案

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

So you want to trigger some method of child directive from parent directive. Unfortunately, AngularJS has no native support for such kind of problem. Here are some workaround for your consideration

  1. 使用内置事件调度程序,这里是一个很好的解释.
  2. 基于组件的 $onChanges 方法,此处描述
  3. 每个 Angular 服务都是一个单例,因此您可以创建一个 服务,用于亲子沟通.
  1. Use built-in event dispatcher, here is a good explanation.
  2. Component-based $onChanges approach, described here
  3. Each angular service is a singleton, therefore you can create a service, intended for parent-to-child communication.

每种方法都很丑陋!

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

我想有一些原因导致它不被本地支持.如果您在 shopAppFormCustomer 父指令下有两个或多个 指令怎么办?并且您想调用一个特定userForm 指令的resetUserFn,如何区分一个userForm 和另一个userForm?

I suppose that there are some reasons why it is not natively supported. What if you have two or more <user-form reset-user-fn=""></user-form> directives under shopAppFormCustomer parent directive? And you want to call to resetUserFn of one particlurar userForm directive, how to distinguish one userForm from another userForm?

Angualar 2 及更高版本以某种方式支持了这一点,但该解决方案也不完美.因此,您只需从上面选择哪个解决方案对您来说痛苦较小并处理它.

This was somehow supported in Angualar 2 and higher, but the solution is not perfect either. So you have just to choose which solution from above is less painful for you and deal with it.

这篇关于触发属性作为 angularjs 指令的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 17:04