Search code examples
angularjsangularjs-directiveangular-directive

Angular nested directive render via ng-repeat


I have a directive that is used to render a single user's details.

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

I have another directive that nests a repeated collection on the user-directive.

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

I've tried setting the scope in the single user directive but I can't seem to get the template to populate with the user data from the repeater.

User directive object:

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

User directive template:

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

Any ideas?

Refer fiddle here for reproducing the effect.


Solution

  • Refer the sample here.

    Code:

    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>"
        }
    });