2014-12-03 23 views
0

我想創建一些自定義標籤與ng-repeat使用angularjs,但它不工作,它給雙引號標記名稱。如何使用ng-repeat生成自定義html標籤或指令?

好結果是:不應該顯示<div>或其他標籤。

我在這裏有一個演示版本:http://plnkr.co/edit/aT2UjMIGGLvnCGFxXC3a?p=preview 或者您可以使用代碼片段

我的代碼是:

angular.module('myApp', []) 
 
.controller('MainCtrl', function($scope) { 
 
    $scope.items = [ 
 
\t { 
 
\t  "name":"directive1" 
 
\t }, 
 
\t { 
 
\t  "name":"directive2" 
 
\t }, 
 
\t { 
 
\t  "name":"div" 
 
\t } 
 
\t ]; 
 
}) 
 

 
.directive("showitems", function(){ 
 
\t return { 
 
\t \t restrict: "E", 
 
\t \t template: '<div class="item" ng-repeat="item in items"><div class="item-title">{{item.name}}</div><div class="item-body"><{{item.name}}></{{item.name}}></div></div>' 
 
\t } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="MainCtrl"> 
 
    <showitems></showitems> 
 
</div>

+0

你只是想顯示標籤喜歡或呈現爲HTML? – Harsh 2014-12-03 14:02:10

+0

@哈爾斯,是的,它正是我想要的,我想渲染他們:) – 2014-12-03 14:11:54

回答

1

而不是將{{item.name}}包裝到其自己的標記中,請生成customTag指令。這可以採用一個字符串(標籤名稱)並使用它創建和編譯一個元素。

.directive("customTag", function ($compile) { 
    return { 
    restrict: "A", 
    link: function (scope, element, attrs) { 
     //pass customTag in as part of the directive attribute 
     var customTag = attrs.customTag; 
     if (!customTag) return; 
     var customElem = angular.element("<" + customTag + "></" + customTag + ">"); 

     //replace your custom element directive with the compiled one 
     element.replaceWith($compile(customElem)(scope)); 
    } 
    } 
} 

然後在您的template.html:

<div class="item" ng-repeat="item in items"> 
    <div class="item-title">{{item.name}}</div> 
    <div class="item-body"> 
     <!-- This will use customTag directive to create element item.name --> 
     <div data-custom-tag="{{item.name}}"></div> 
    </div> 
</div> 

,因爲它沒有得到任何的innerHTML或行爲類似指令1 div標籤(或任何非指令)將不會太有用,指令2會得到。這當然是一個簡單的例子,你可能想在那裏放一些檢查或限制,但這應該讓你開始。

查看小提琴here建立在您的示例上。

+0

非常感謝幫助:) – 2014-12-03 14:25:40

2

據我所知,做這樣的事情<{{item.name}}></{{item.name}}>行不通的因爲標記不被視爲新的DOM元素。一種更好,更易於管理的方法是爲所有可能的想要呈現爲DOM元素的types編寫指令。

同時,更多地瞭解DOM操作從指令中,閱讀了有關$compilehere

這樣做會是這樣在你的指令模板的另一種方法:

<directive1 ng-if="directiveType == 'directive1'"></directive1> 
<directive2 ng-if="directiveType == 'directive1'"></directive2> 
<directive3 ng-if="directiveType == 'directive1'"></directive3> 

在您的控制器/指令中,您必須聲明directiveType以指定要呈現的指令類型。

+0

感謝您的幫助,我給你upvote,你能給我一個例子,我如何使用'$ compile'做這個工作。 – 2014-12-03 14:14:34

+0

這對我來說有點難,因爲我不知道你想在這裏實現的內容。我會添加一些代碼給我的答案,你可能會發現更簡單的方法,以便你明白。 – Ashesh 2014-12-03 14:18:12

+0

非常感謝您向我展示的方式,我接受使用前面說過的'$ compile'的帕特里克,但他說了更多細節,再次感謝:) – 2014-12-03 14:28:03

相關問題