在AngularJs中,父指令如何调用在其子指令中定义的函数
In AngularJs , how does the parent directive call the function which is defined in its child directive?
我想调用子指令中的函数,而不是使用$scope.$broadcast
通知子指令发生了什么事情。外部指令将在不同的时间调用不同子指令中的不同函数。
您可以在指令中使用控制器
例如:在子指令的链接函数中,您可以将所需内容保存在父控制器中,然后在需要时调用。
样品
angular.module('app', [])
.directive('parent', function() {
return {
controller: function() {
var parent = this;
parent.childs = [];
parent.click = function() {
parent.childs.forEach(function(child) {
child.addOne();
});
}
},
controllerAs: 'vm'
}
})
.directive('child', function() {
return {
require: ['child', '^parent'],
template: '<div>Child value: {{vm.val}} <input type="button" ng-click="vm.addOne()" value="add one" /></div>',
controller: function() {
var child = this;
child.addOne = function() {
child.val += 1;
}
},
controllerAs: 'vm',
scope: true,
link: function(scope, elem, attrs, ctrls) {
var childCtrl = ctrls[0],
parentCtrl = ctrls[1];
parentCtrl.childs.push(childCtrl);
childCtrl.val = +attrs.child;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<div ng-app="app">
<div parent>
<input type="button" ng-click="vm.click()" value="add one to all" />
<div child="1"></div>
<div child="2"></div>
<div child="3"></div>
</div>
</div>
我们需要在父指令作用域中创建一个空对象,并将其作为参数传递给子指令。
在子指令中接收它时,我们可以向它注入方法
app.directive('childDirective', function () {
return {
restrict: 'E',
scope: {
objectToInject: '=',
},
templateUrl: 'templates/myTemplate.html',
link: function ($scope, element, attrs) {
var killwatch = $scope.$watch('objectToInject', function (value) {
if(value){
$scope.Obj = value;
/*Injecting the Method*/
$scope.Obj.invoke = function(){
//Do something
}
killwatch();
}
});
}
};
});
并使用该对象从父对象调用子指令函数。
相关文章:
- AngularJS指令出错-无法读取属性'编译'的未定义
- AngularJS指令单元测试中未定义的函数
- 错误:[$compile:nonassign]表达式'未定义'与指令'内容可编辑'是不可
- 如何在自定义指令中获取计算的属性
- 向动态生成的DOM添加Angular自定义指令
- 自定义指令中的AngularJS ng模型
- 如何在html中以角度显示自定义指令的作用域
- AngularJS自定义日期选择器指令
- 自定义指令模板中的AngularJS控制变量
- 与ng attr myCustomAttribute匹配的自定义属性指令
- 角度指令控制器:参数不是函数,未定义
- 使用 Angular.Module 的 AngularJS 指令定义
- 为什么角度为在同一 DOM 元素上定义的指令定义“优先级”属性
- 是否可以从指令定义内部访问指令的实例
- 返回指令定义中的对象和函数之间的区别
- 如何在指令定义期间将新指令正确添加到指令中
- 在指令定义中使用$compile的意义是什么?
- 指令定义语法澄清
- Angular JS指令定义——需要ngModelController和自定义控制器
- 在{}和link中为angular指令定义独立作用域变量的区别