我将此 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 没有对此类问题的原生支持。以下是一些供您考虑的解决方法
- 使用内置事件调度程序,here is一个很好的解释。
- 基于组件的 $onChanges 方法,described here
- 每个 Angular 服务都是一个单例,因此您可以创建 service ,用于亲子沟通。
每种方法都非常丑陋!
- 事件调度程序 - 太多的事件可能会显着降低应用程序的速度。您最终可能会遇到数百个事件,这确实很难维护。
- $onChanges - 代码看起来很难看,难以维护。
- 每个案例都需要一个新的服务,这很难维护。
我认为有一些原因导致它不受 native 支持。如果您有两个或更多<user-form reset-user-fn=""></user-form>
怎么办? shopAppFormCustomer
下的指令家长指令?您想调用 resetUserFn
某一特定的userForm
指令,如何区分userForm
来自另一个userForm
?
Angualar 2 及更高版本以某种方式支持这一点,但该解决方案也不完美。因此,您只需从上面选择一种对您来说不那么痛苦的解决方案并进行处理即可。
关于javascript - 触发属性作为 angularjs 指令的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53910880/