AngularJs将指令的元素附加到其模板中

时间:2015-10-10 12:51:24

标签: angularjs angular-directive

我如何将指令元素附加到其模板? 像这样:

.directive('labelize',function(){
   return {
      restrict: 'A',
      template: '<div><ng-element/></div>'
      ...
   }
});

# Html
// <input labelize name="name"/>

# Output
// <div><input name="name"/></div>

更新

当我使用此指令时:

app.directive 'labelize', () ->
      restrict: 'A'
      requrie: 'input'
      controller: [
           '$scope', '$element', '$attrs',
           ( $scope , $element , $attrs ) ->
                  $scope.label = $attrs.placeholder
      ]
      replace: true
      transclude: 'element'
      template: '<div class="labelize"><span class="label">{{ label }}</span><ng-transclude/></div>'

使用这个html:

<input labelize placeholder="Name" ng-class="{ 'red': true }" ng-focus="Focused()"/>

<!-- Angular compiled output -->
<div class="labelize" labelize placeholder="Name" ng-class="{ 'red': true }" ng-focus="Focused()" class="red">
    <input labelize placeholder="Name" ng-class="{ 'red': true }" ng-focus="Focused()"/>
</div>

ngFocus,ngClass或任何ng属性在labelize指令后无效。

1 个答案:

答案 0 :(得分:0)

您可以使用transclue:&#39;元素&#39;为了这 。

 .directive('labelize',function(){
    return {
        restrict: 'A',
        template: "<div ng-transclude></div>",
        replace:true,
        transclude: "element",


    }

输入:<input labelize name="name" />

输出:<div labelize="" name="name" ng-transclude=""><input class="ng-scope" labelize="" name="name"></div>

我希望它适合你。