创建Angular Directive说Undefined不是一个函数

时间:2014-04-27 08:53:37

标签: javascript angularjs

我想创建自己的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>'
};
}])

2 个答案:

答案 0 :(得分:1)

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

因此,为了使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
 };
}]);

<强> Hierarchey

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>'
 };
}])

答案 1 :(得分:1)

我没有深入研究代码,只是试图解决主要问题。 问题源于你没有宣布应用程序本身。

看看这里: http://jsbin.com/rituvogu/2/edit

我已宣布该应用,问题已解决(关于其余代码 - 这是另一回事:)。)。