自定义指令内的ng-repeat

时间:2014-06-03 17:39:56

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

所以我正在努力将范围传递给我的自定义指令。

这是我的HTML

<li ng-repeat="post in posts | filter:search | orderBy:sortField:reverse" class="archives-listing" ng-class="{'last-border':$last}">

    <archive-notes></archive-notes>


</li>

这是我的指示

app.directive('archiveNotes', function(){
return {
    restrict: 'E',
    transclude: true,
    scope: {
        notes: '@',
        paths: '@'
    },
    controller: function($scope) {

    },
    templateUrl: '/wp-content/themes/twentythirteen/js/angular/templates/notes.html'
}
})
app.directive('archiveFolders', function(){
return {
    require: '^archiveNotes',
    restrict: 'E',
    transclude: true,
    scope: {
        path: '@'
    },
    link: function(scope, element, attrs) {

    },
    templateUrl: '/wp-content/themes/twentythirteen/js/angular/templates/folders.html'
}
});

这是我的模板。

notes.html
<div ng-class="{'found' : find(post.paths[$index], search)}" class="arch-notes">
    <div ng-bind-html="is_NotesEmpty(post.notes)">{{post.notes}}</div>
    <archive-folders></archive-folders>
</div>

folders.html
<div ng-repeat="path in post.paths | filter:search track by $index" ng-transclude>
    <span class="arch-paths">{{path}}</span>
</div>

我留下了几个空白i.e controller and link,因为此时我只想弄清楚在开始操作DOM之前如何让所有内容都显示出来

我按照angularjs文档中的示例进行操作,这让我感到非常兴奋。我想似乎无法弄清楚如何访问范围?

感谢任何帮助。

1 个答案:

答案 0 :(得分:5)

根据您的模板,您的archiveNotes指令定义看起来应该是这样的:

app.directive('archiveNotes', function(){
return {
    ...
    scope: {
        post: '='
    },
    ...
}
})

要获取从post范围传入的ng-repeat变量,您还需要在指令的元素上设置post属性:

<archive-notes post="post"></archive-notes>

同样,您需要在子指令上设置它:

app.directive('archiveFolders', function(){
return {
    ...
    scope: {
        post: '='
    },
    ...
}
});

...并更改您的notes.html模板:

<archive-folders post="post"></archive-folders>

隔离范围有点像防火墙,您可以在其中设置异常,在本例中为特定范围变量。我们在这里所做的就是在指令定义中设置这些异常,然后使用元素上的属性传递它们。

John Lindquist的这些视频真的为我提供了一些关于孤立范围的视频: