Angular嵌套指令通过ng-repeat渲染

时间:2016-02-21 00:42:05

标签: angularjs angularjs-directive angular-directive

我有一个用于呈现单个用户详细信息的指令。

<user-directive></user-directive/>

我有另一个指令,它在用户指令上嵌套重复的集合。

<!-- has some other stuff then the user collection -->
<user-directive ng-repeat="user in vm.users" user="user"></user-directive>

我已尝试在单用户指令中设置范围,但我似乎无法使用转发器中的用户数据填充模板。

用户指令对象:

return {
          // template etc
          scope : { user: '=' }
       }

用户指令模板:

<h1>{{user.name}}</h1>

有什么想法吗?

请参阅fiddle here以复制效果。

1 个答案:

答案 0 :(得分:2)

参考样本here

<强>代码:

HTML:

<div ng-app="app" ng-controller="test as vm">
    <div test-dir="user" ng-repeat="user in vm.users">
    </div>
</div>

JS:

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

app.controller('test', function ($scope) {
    var vm = this;
    vm.users = [
     { 'Name': 'Abc', 'Id': 1 }, { 'Name': 'Pqr', 'Id': 2 }, { 'Name': 'XYZ', 'Id': 3 }
    ];

    $scope = vm;
});

app.directive('testDir', function () {
    return {
        scope: { user: '=testDir' },
        template: "<div><h4>{{user.Id}}) {{user.Name}}</h4></div>"
    }
});
相关问题