Angularjs使用ng-repeat动态创建指令

时间:2014-07-14 08:10:07

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

我想知道有没有办法用ng-repeat创建动态指令。像这样的东西:

<div ng-repeat="document in documents">
    <div document.name></div>
</div>

1 个答案:

答案 0 :(得分:0)

您可以使用属性来执行此操作。例如:

    <div ng-repeat="document in documents">
       <document-viewer name="document.name"></document-viewer>
    </div>

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

    app.controller("AppCtrl", function($scope) {
        $scope.documents = [
            {id:1, name:'document1'},
            {id:2, name:'document2'}
        ];
    });

    app.directive("documentViewer", function() {
        return {
           scope: {
                //attribute name will match the name passed from your view,
                //and you will be able to use it on your template or logic
                name: "="
           },
           //Add your template here:
           template: '<div><button ng-click="openDocument(name);"></div>',
           //Add your logic here:
           link: function(scope, element, attrs){ ... }
        }
    });

我不知道这是否能回答你的问题,但你并不清楚你想要达到的目标是什么。

查看以下视频,因为它们在处理指令和隔离范围时可能会对您有用:

http://egghead.io/lessons/angularjs-directive-to-directive-communication

http://egghead.io/lessons/angularjs-isolate-scope-expression-binding

http://egghead.io/lessons/angularjs-isolate-scope-attribute-binding

http://egghead.io/lessons/angularjs-isolate-scope-two-way-binding

相关问题