繁体   English   中英

AngularJS:如何访问已包含内容中的指令范围?

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

我很难让我的包含指令生效。 我要执行以下操作:创建一个指令,该指令输出一个列表,其中每个项目的内容均由被包含的内容定义。 例如:

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

因此,我将在op-list的模板中使用ng-repeat,并且必须能够访问已包含在内的内容中ng-repeat创建的范围。

到目前为止,这是我所做的:

 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> 

检查是否可行:

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: '='
        }
    };
}]);

如果没有,请尝试在控制台中检查$ scope,看看是否能够访问模型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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