gpt4 book ai didi

javascript - AngularJS 指令要求父指令不起作用

转载 作者:行者123 更新时间:2023-11-30 08:03:24 24 4
gpt4 key购买 nike

我想制作一个带有复选框(这是一个递归列表)指令的类别树。

我做了一个名为 categoriesTreeContainer 的指令,其中包含所有类别列表

我做了另一个名为 categoryItem 的指令,其中包含类别项,它是 categoriesTreeContainer 的子项/p>

这就是我所做的 categoriesTreeContainer:

myApp.directive('categoriesTreeContainer', function(){
return {
restrict : 'E',
template : '<category-item ng-repeat="category in categoriesTree" category="category"></category-item>',
scope : {
categoriesTree : "=categoriestree",
selectedCategories : "=ngModel",
},

controller : function($scope, $element, $attrs){
$scope.selectedCategories = [];

$scope.onSelectionChange = function(category){
console.log('yah');
}
}
}

})

对于 categoryItem:

myApp.directive('categoryItem', function($compile){
return {
require: '^categoriesTreeContainer',
restrict : 'E',
//replace : true,
transclude : true,
scope : {
category : "=category"
},
link : function(scope, element, attrs, categoriesTreeCtrl){
console.log(categoriesTreeCtrl);

if(scope.category.subCategories.length>0){

element.append($compile(
'<div class="panel panel-default panel-treelist">'+
'<div class="panel-heading"><h4 class="panel-title">'+
'<label data-toggle="collapse" data-target="#{{category.$$hashKey}}">'+
'<input type="checkbox" ng-change="categoriesTreeCtrl.onSelectionChange(category)" ng-model="category.selected" />'+
' {{category.name}}</label></h4></div><div id="{{category.$$hashKey}}" class="panel-collapse collapse">'+
'<div class="panel-body">'+
'<category-item id="{{category.$$hashKey}}" ng-repeat="subCategory in category.subCategories" category="subCategory" categoriestree="categoriesTree" ng-model="selectedCategories">'+
'</category-item></div></div></div>'
)(scope))
}else{
element.append($compile('<label><input ng-change="categoriesTreeCtrl.onSelectionChange(category)" type="checkbox" ng-model="category.selected"> {{category.name}}</label><br/>')(scope));
}
}
}

})

在 DOM 中:

<categories-tree-container categoriestree="categoriesTree" ng-model="selectedCategories"></categories-tree-container>

这棵树是按我想要的方式渲染的。问题是 categoryItem 指令中的 required Controller “^categoriesTreeContainer”无效。我在 link 函数中为 categoriesTreeCtrl 做了一个 console.log(categoriesTreeCtrl),这就是我得到的:

c {},一个空对象。

我做错了什么?

最佳答案

categoriesTreeCtrl 将是 void object 因为 Controller 什么都没有。如果您需要从子指令访问 categoriesTreeCtrl.onSelectionChange,您不应将 onSelectionChange 作为其 $scope 的一部分,而是将其定义为 Controller 的属性。

controller: function($scope, $element, $attrs){
this.onSelectionChange = function(category){ ... };
// $scope.onSelectionChange = function(category){...}
}

附加:
child 指令上的 categoriesTreeCtrl 不等于 $scope.categoriesTreeCtrl,这意味着您无法从模板中调用 categoriesTreeCtrl。查看 ng-change 值。

关于javascript - AngularJS 指令要求父指令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22590996/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com