2014-10-26 14 views
0

Angular documentation的示例中,可以通過將其名稱作爲屬性放在<div>中來使用指令。給出的例子是爲什麼指令不起作用,如果我把名稱作爲屬性而不是標籤?

<div ng-controller="Controller"> 
    <div my-customer></div> 
</div> 

與JS看上去就像

angular.module('docsSimpleDirective', []) 
    .controller('Controller', ['$scope', function($scope) { 
    $scope.customer = { 
     name: 'Naomi', 
     address: '1600 Amphitheatre' 
    }; 
    }]) 
    .directive('myCustomer', function() { 
    return { 
     template: 'Name: {{customer.name}} Address: {{customer.address}}' 
    }; 
    }); 

然而,在一個類似的例子,在這裏,如果我的html代碼更改從<tree><div tree>,代碼不再工作。

爲什麼不呢?

從JS小提琴代碼:

<div ng-app="myapp"> 
    <div ng-controller="TreeCtrl"> 
     <tree family="treeFamily"> 
      <p>{{ family.name }}</p> 
     </tree> 
    </div> 
</div> 


var module = angular.module('myapp', []); 

module.controller("TreeCtrl", function($scope) { 
    $scope.treeFamily = { 
     name : "Parent", 
     children: [{ 
      name : "Child1", 
      children: [{ 
       name : "Grandchild1", 
       children: [] 
      },{ 
       name : "Grandchild2", 
       children: [] 
      },{ 
       name : "Grandchild3", 
       children: [] 
      }] 
     }, { 
      name: "Child2", 
      children: [] 
     }] 
    }; 
}); 

module.directive("tree", function($compile) { 
    return { 
     restrict: "E", 
     transclude: true, 
     scope: {family: '='}, 
      template:  
      '<ul>' + 
       '<li ng-transclude></li>' + 
       '<li ng-repeat="child in family.children">' + 
        '<tree family="child">{{family.name}}</tree>' + 
       '</li>' + 
      '</ul>', 
     compile: function(tElement, tAttr, transclude) { 
      var contents = tElement.contents().remove(); 
      var compiledContents; 
      return function(scope, iElement, iAttr) { 
       if(!compiledContents) { 
        compiledContents = $compile(contents, transclude); 
       } 
       compiledContents(scope, function(clone, scope) { 
         iElement.append(clone); 
       }); 
      }; 
     } 
    }; 
}); 

tree { 
    margin-left: 20px; 
    display: block; 
} 

回答

2

的限制選項用於指定如何指令可以在頁面上被調用。有四種不同的方式來調用指令,所以有限制四個有效選項:

'A' - attribute - <span ng-sparkline></span> 
'E' - element - <ng-sparkline></ng-sparkline> 
'C' - class - <span class="ng-sparkline"></span> 
'M' - comment - <!-- directive: ng-sparkline --> 

在你的情況下,它不工作,因爲它被定義爲限制「E」 - 元素。

相關問題