gpt4 book ai didi

javascript - 将数据传递给嵌入元素

转载 作者:行者123 更新时间:2023-11-28 06:58:43 25 4
gpt4 key购买 nike

我想创建一个指令来组织按日期分组的显示数据。我还希望能够指定一个显示各个行的指令。在完美的世界中,它看起来像这样(但又漂亮又漂亮)

Friday, Oct 28
[some directive html]
[some directive html]
[some directive html]
Saturday, Oct 29
[some directive html]
Sunday, Oct 30
[some directive html]
[some directive html]
...

这显然行不通,所以如果您有更好的方法请告诉我,但我希望能够按照以下方式做一些事情:

app.directive('dateOrganized', [function(){
return {
template:
'<div>' +
'<div ng-repeat="organizedDate in organizedDate">' +
'<div>{{organizedDate.date | date}}</div>' +
'<div ng-repeat="item in organizedDate.items">' +
'{{rowDirectiveHtml}}' +
'</div>' +
'</div>' +
'</div>',
scope: {
organizedDates: '=',
rowDirectiveHtml: '='
}
...
};
}])

app.directive('itemRow', [function(){
return {
template: '<div>{{item.data}}</div>',
scope: {
item: '='
}
};
}]);

然后像这样使用它:

<div data-organized organized-dates="stuff" row-directive-html="<div item-row item=\"item\" />" />

我知道这非常丑陋(而且不起作用,但我确信我可以通过一些调整让它工作)所以我真正要问的是,有没有更好的方法来做到这一点?

最佳答案

这个问题比看上去要复杂,所以让我们来分解一下。

您正在构建的是一个接受部分模板的指令 - <div item-row item="item" /> - 该模板使用内部变量(或链接到范围)- item - 未由用户在外部范围中定义;它的含义由您的指令定义,并且您的用户通过阅读指令的文档“发现”它。我通常用前缀 $ 来命名此类“神奇”变量。 ,例如$item .

第 1 步

不要通过属性绑定(bind)将模板作为 HTML-as-string 传递,而是将其作为内容传递并嵌入该内容。嵌入允许您将嵌入的内容绑定(bind)到任意范围:

<foo>
<div>my item is: {{$item}}</div>
</foo>
.directive("foo", function(){
return {
scope: {},
transclude: true,
template: "<h1>I am foo</h1><placeholder></placeholder>",
link: function(scope, element, attrs, ctrls, transclude){

scope.$item = "magic variable";

transclude(scope, function(clonedContent){
element.find("placeholder").replaceWith(clonedContent);
});
}
};
});

上面将放置模板<div>my item is: {{$item}}</div> (可以是您指定的任何模板)其中指令 foo决定,并将链接到具有 $item 的范围已定义。

第 2 步

但是指令的复杂性在于它使用 ng-repeat ,它本身接受一个模板,并且您的指令接收的模板需要用作 ng-repeat 的模板。

仅使用上面的方法,这是行不通的,因为到了 link运行,ng-repeat在您有机会应用您的内容之前,它已经嵌入了自己的内容。

解决该问题的一种方法是手动 $compile foo的模板而不是使用 template属性(property)。在编译之前,我们将有机会将预期的模板放置在需要的地方:

.directive("foo", function($compile){
return {
scope: {},
transclude: true,
link: function(scope, element, attrs, ctrls, transclude){

scope.items = [1, 2, 3, 4];

var template = '<h1>I am foo</h1>\
<div ng-repeat="$item in items">\
<placeholder></placeholder>\
</div>';
var templateEl = angular.element(template);

transclude(scope, function(clonedContent){
templateEl.find("placeholder").replaceWith(clonedContent);

$compile(templateEl)(scope, function(clonedTemplate){
element.append(clonedTemplate);
});
});
}
};
});

<强> Demo

关于javascript - 将数据传递给嵌入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32336469/

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