gpt4 book ai didi

javascript - 你能在 Angular 中嵌入一个子指令吗?

转载 作者:数据小太阳 更新时间:2023-10-29 04:19:05 24 4
gpt4 key购买 nike

我希望能够在我的应用中做这样的事情:

<pill-autocomplete>
<pill-template>{{item.name}}</pill-template>
</pill-autocomplete>

在哪里pill-autocomplete有一个像这样嵌入到子指令中的模板:

<pills ng-transclude="pillTemplate"></pills>
<input type="text">

考虑到 ng-transclude 创建范围和 <pills> 这似乎是不可能的指令具有隔离作用域。

我想到的实现此目的的一种方法是将 pill 模板注入(inject)自动完成的模板函数中。问题在于它失去了包含范围。我还必须在每个与药丸有类似行为的指令中执行此操作。

在 Angular 1.x 中有没有其他方法可以实现这一点?

最佳答案

问题是,当您将数据从 pill-autocomplete 转入 pill 时,您已经删除了 pill 中的内容。

嵌入替换了指令模板下的内容,因此 pills 指令模板中的内容根本无法加载,因为已被嵌入覆盖。

我的建议很简单,不要直接使用里面有ng-transclude的标签,使用一个内部div来让指令加载它的内容成为可能

angular.module('app', []);
var app = angular.module('app');

'use strict';

var app = angular.module('app');

app.controller('testController', [
function () {
var vm = this;
vm.name = 'Jimmy';
}]);

app.directive('pillAutocomplete', function () {
return {
priority: 100,
restrict: 'E',
transclude: true,
template: '<pills><p>From Pill-Autocomplete</p><div ng-transclude><div></pills>'
};
});

app.directive('pills', function () {
return {
restrict: 'E',
transclude: true,
link: function (scope, element, attrs) {
scope.style = true;
},
template: '<p>Inside Pills</p><div ng-class="{pillscolor : style}" ng-transclude></div>'
};
});
.pillscolor{
color: green;
font-size: 20px;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<article ng-app="app">
<section ng-controller="testController as test">
Controller scope - {{test.name}}
<pill-autocomplete>
From controller - {{test.name}}
</pill-autocomplete>
</section>
</article>

关于javascript - 你能在 Angular 中嵌入一个子指令吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40698188/

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