简体   繁体   中英

AngularJS : How to access the directive's scope in transcluded content?

I have trouble getting my transcluding directive to work. I want to do the following: Create a directive that outputs a list where the content of each item is defined by transcluded content. Eg:

<op-list items="myItems">
  <span class="item">{{item.title}}</span>
</op-list>

so I would use ng-repeat inside op-list's template and must be able to access the scope created by ng-repeat inside the transcluded content.

This is what I've done so far:

 var myApp = angular.module('myApp', []); myApp.controller('MyCtrl', ['$scope', function ($scope) { $scope.myModel = { name: 'Superhero', items: [{ title: 'item 1' }, { title: 'item 2' }] }; }]); myApp.directive('opList', function () { return { template: '<div>' + '<div>items ({{items.length}}):</div>' + '<div ng-transclude ng-repeat="item in items"></div>' + '</div>', restrict: 'E', replace: true, transclude: true, scope: { items: '=' } }; }); 
 <html ng-app="myApp"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-controller="MyCtrl"> <div>Hello, {{myModel.name}}!</div> <op-list items="myModel.items"> <span>title: {{item.title}}|{{$scope}}|{{scope}}|{{items}}</span> </op-list> </div> </html> 

Check if this works:

myApp.directive('opList', ['$scope', function ($scope) {
    return {
        template: '<div>' +
            '<div>items ({{model.items.length}}):</div>' +
            '<ng-transclude ng-repeat="item in model.items"></ng-transclude>' +
            '</div>',
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: {
            items: '='
        }
    };
}]);

If it doesn't then try to inspect $scope in console and see if you're able to access your model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM