本文介绍了触发属性作为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方法,在此处描述的/a>
  3. 每个角度服务都是一个单例,因此您可以创建一个服务,用于父母与孩子之间的交流.
  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父指令下有两个或多个<user-form reset-user-fn=""></user-form>指令怎么办?并且您想调用一个特殊的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