2013-04-21 22 views
1

我想實現我自己的ng-repeat版本。但不知何故,我無法得到它的工作,因爲jquery append方法似乎不工作。在AngularJS中,jquery append方法似乎不適用於指令

的script.js:

var app = angular.module("app", []); 

app.directive("myRepeat", function() { 
    return { 
    restrict: 'E', 
    compile: function(element, attrs) { 
     var c = element.children()[0]; 
     console.log(c) 
     for(var i=0; i<attrs.times; i++) { 
     element.append(c); 
     } 
     return function(scope, element, attrs) { 
     $(element).click(function() { 
      console.log("hi"); 
     }) 
     } 
    } 
    } 
}) 

的index.html:

<body ng-app="app"> 
    <my-repeat times="5"><p>hello world</p></my-repeat> 
</body> 

Code in use at plnkr.co

+4

我編輯了你的文章,但下次;請在SO上發佈您的代碼,我們不應該爲了閱讀您的代碼而轉到其他頁面。例如,可以在同一頁面上提供代碼,方便您寫答案等。 – timss 2013-04-21 00:45:49

+0

會做。謝謝timss! – lkahtz 2013-04-21 19:41:36

回答

1

我在閱讀了一段jQuery代碼後找到了答案。追加將在附加DOM元素時檢查並刪除重複。我收拾c到DOM列表,並改變了追加線在我的for循環爲:

element.append(c.clone()); 

,問題就消失了。

相關問題