[英]element.find() not working when using templateUrl in directive
[英]Retrieving child directive scope from parent through element.find
我不能使用“ require”,因为我有一个指令,可以有很多不同的父母,但我无法确切预测他们的身份。 我需要做的是在每个父级中能够检索控制器或子级指令的范围并调用禁用按钮的方法。 我有一个显示问题的插件。
https://plnkr.co/edit/Od1mJZOq1ep54pj6k6ti?p=preview
.directive('parent', function($compile, $rootScope) {
return {
restrict: 'E',
scope: {},
templateUrl: 'parent.html',
link: postLinkFunction
};
function postLinkFunction(scope, element, attributes) {
var directive = element.find('child');
var directiveScope = directive.isolateScope();
console.log(directiveScope);
}
})
.directive('anotherParent', function() {
return {
restrict: 'E',
scope: {},
templateUrl: 'parent.html',
link: postLinkFunction
};
function postLinkFunction(scope, element, attributes) {
var directive = element.find('child');
var directiveScope = directive.isolateScope();
console.log(directiveScope);
}
})
.directive('child', function() {
return {
restrict: 'E',
scope: {},
controller: function($scope, $element) {
var vm = this;
$scope.isDisabled = false;
$scope.disableMenu = function () {
$scope.isDisabled = true;
};
$scope.number = 1;
},
templateUrl: 'child.html'
};
});
即使我已经填充了isolateScope,它也为空,子指令也必须具有isolate范围,不能与父级共享范围,并且正如我所说,我不能使用require。 从理论上讲,element.find方法是很笨拙的,但易于实现,但我无法使其工作。 任何帮助表示赞赏,在此先感谢!
在角度链接过程是从上到下执行的,因此,在您尝试创建子作用域之前,您可以通过在作用域中添加功能并在单击时执行它来解决此问题:
scope.click = function() {
var directive = element.find('child');
var directiveScope = directive.isolateScope();
console.log(directiveScope);
};
<div class="tabbable">
<div class="tab-content">
<child></child>
</div>
<button ng-click="click()">click</button>
</div>
您的父模块应通过隔离范围内的变量与子代进行通信,如下所示:
app.directive("testDir", function() {
var directive = {
restrict: "A",
template: "<div><input value='TestButton' type='button' data-ng-disabled='IsDisabled'></div>",
scope:
{
IsDisabled: "=isDisabled"
}
};
return directive;
});
这是工作演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.