gpt4 book ai didi

javascript - 如何在指令模板中将嵌入元素的范围更改为 ng-repeat 项范围

转载 作者:行者123 更新时间:2023-12-03 07:48:45 25 4
gpt4 key购买 nike

我希望能够获取嵌入的内容。将其应用于指令内的 ng-repeat。然后将每个 ng-repeat 的范围应用于嵌入内容的克隆。

在另一个指令A的一部分中我有这个:

...

<directive-b>
// title is exposed here to directiveA but I want it to be changed to ng-repeat scope later
<p>Hello {{title}}</p>
</directive-b>

...

directiveB 指令内部

(function() {
'use strict';
angular.module('app')
.directive('directiveB', DirectiveB);

function DirectiveB() {
return {
restrict: 'E',
transclude: true,
scope: {},
bindToController: {},
compile: DirectiveBCompile,
controller: DirectiveBController,
controllerAs: 'vm',
templateUrl: 'directive-b.partial.html'
}
}

function DirectiveBCompile(cElem, cAttr, cTransclude) {
// cTransclude is deprecated... so cant do this here
return InfiniteScrollLink;
}

function DirectiveBController() {
var vm = this;
}

function DirectiveBLink(scope, element, attrs, controller, transclude) {
// ideally would be great to somehow apply ng-repeat scope to each transcluded element here, but I couldn't

scope.data = [{
title: 12345
}, {
title: 345245
}, {
title: 32452345
}];
// this scope doesn't get picked up either
scope.title = "12345";
}
})();

directiveB 指令部分内部

<ul>
<li data-ng-repeat="data in vm.data" data-ng-transclude>
</li>
</ul>

有什么方法可以将 ng-repeat 中的“数据”作为嵌入范围传递吗?

我想看到的是:

<ul>
<li>
<p>Hello 12345</p>
</li>
<li>
<p>Hello 345245</p>
</li>
<li>
<p>Hello 32452345</p>
</li>
</ul>

最佳答案

我能够以一种非常肮脏的方式做到这一点。

<directive-b>
// just want to point out that this is **probably** the only way to pass
// data-bind inside this element as otherwise scope would be overwritten
<div ng-controller="DirectiveBTemplate as template">
<p>Hello {{template.data.title}}</p>
</div>
</directive-b>

那么,

<ul>
// data="data" is crucial here, basically sets data to ng-repeat scope
<li data-ng-repeat="data in vm.data" data="data" data-ng-transclude>
</li>
</ul>

然后,

(function() {
'use strict';
angular.module('app.widgets')
.controller('DirectiveBTemplate', DirectiveBTemplate)
.directive('directiveB', DirectiveB);
DirectiveBTemplate.$inject = ["$scope"];

function DirectiveBTemplate($scope) {
// I'm basically assigning ng-repeat scope and setting it to DirectiveBTemplate scope, them im retrieving data from ng-repeat.
$scope = $scope.$parent.$parent;
this.data = $scope.data;
}

关于javascript - 如何在指令模板中将嵌入元素的范围更改为 ng-repeat 项范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35093195/

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