gpt4 book ai didi

javascript - 创建 Angular 指令说未定义不是函数

转载 作者:行者123 更新时间:2023-12-02 17:28:11 24 4
gpt4 key购买 nike

我想创建自己的 TreeView 指令,但出现此错误:

TypeError: undefined is not a function

代码是here

我的指令代码是:

  app.directive('tree', [function () {
return {
scope:{
treeModel:'='
},
restrict: 'AE',
template:'<ul><li ng-repeat="root in treeModel">{{root.name}}'+
'<ul><li ng-repeat="h in root.hierarchies"><hierarchey hierarchey- model="h"></hierarchey></li></ul>'
+'</li><ul>'
};
}]);
app.directive('hierarchey', [function () {
return {
scope:{
isExpand:false
},
controller:function($scope){
$scope.hierarchyOp = function(){
alert("IM CLIKED");
}
},
restrict: 'AE',
template:'<span ng-click="hierarchyOp()"><i ng-show="isExpand" class="fa fa-folder-open"></i><i ng-hide="isExpand" class="fa fa-folder-open"></i>{{h.name}}</span>'
};
}])

最佳答案

问题的第一部分是两个指令都有隔离范围。

因此,为了让 hierarchey 指令能够通过 heirarcheyModel 变量访问 h 变量,您需要将值传递给该指令。

scope:{
hierarcheyModel: '=' //add this to pass the object to the scope
}

第二部分是因为 ng-repeat 还创建了它自己的作用域,据我所知,它不是父作用域的子作用域。因此,您需要隔离范围,并且必须将变量传递到指令中才能访问它。

树:

app.directive('tree', [function () {
return {
scope:{
treeModel:'='
},
restrict: 'AE',
template:
'<ul>'+
'<li ng-repeat="root in treeModel">{{root.name}}'+
'<ul>' +
'<li ng-repeat="h in root.hierarchies">' +
'<hierarchey hierarchey-model="h"></hierarchey>' +
'</li>' +
'</ul>' +
'</li>'+
'</ul>' //Forgot to close the ul
};
}]);

层次结构

app.directive('hierarchey', [function () {
return {
scope:{
hierarcheyModel: '=' //add this to pass the object to the scope
},
controller:function($scope){
$scope.hierarchyOp = function(){
alert("IM CLIKED");
}
$scope.isExpand = false; // This value should like in the controller not the isolate scope
},
restrict: 'AE',
template:'<span ng-click="hierarchyOp()"><i ng-show="isExpand" class="fa fa-folder-open"></i><i ng-hide="isExpand" class="fa fa-folder-open"></i>{{hieracheyModel.name}}</span>'
};
}])

关于javascript - 创建 Angular 指令说未定义不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23321331/

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