问题描述
我将此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
- Use built-in event dispatcher, here is a good explanation.
- Component-based $onChanges approach, described here
- Each angular service is a singleton, therefore you can create a service, intended for parent-to-child communication.
每种方法都很难看!
- 事件分派器-太多事件可能会大大降低应用程序的速度.您可能会遇到数百个事件,这些事件真的很难维护.
- $ onChanges-代码看起来丑陋,难以维护.
- 每种情况下都需要一项新服务,很难维护.
我认为有一些原因导致本机不支持它.如果在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指令的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!