gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:12:31 26 4
gpt4 key购买 nike

我无法让我的嵌入指令发挥作用。我想要执行以下操作:创建一个输出列表的指令,其中每个项目的内容由嵌入的内容定义。例如:

<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 并查看是否能够访问您的模型。

关于javascript - AngularJS : How to access the directive's scope in transcluded content?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31157159/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com