迭代和提供动态内容定义的数量是与compile
功能+的$compile
服务自定义指令中普遍使用。当心:基本上你正在重复ng-repeat
的功能,你可能想要考虑替代方案。
E.g.而不是articles
列表,请使用另一个(可能名为articlesLimited
)。新列表是动态构建的,包含来自articles
的第一个元素。标志(例如hasMore
)指示原始articles
是否具有更多元素,简单地如下:$scope.hasMore = articles.length > 5
。您使用hasMore
标志来显示/隐藏“+ N多”消息。
但是值得一提的是,下面是sentence
指令的实现。查看弱点的评论!
app.directive('sentence', ['$compile', function($compile) {
var RE = /^([a-z_0-9\$]+)\s+in\s([a-z_0-9\$]+)$/i, ONLY_WHITESPACE = /^\s*$/;
function extractTrimmedContent(tElem) {
var result = tElem.contents();
while(result[0].nodeType === 3 && ONLY_WHITESPACE.test(result[0].textContent)) {
result.splice(0, 1);
}
while(result[result.length-1].nodeType === 3 && ONLY_WHITESPACE.test(result[result.length-1].textContent)) {
result.length = result.length - 1;
}
return result;
}
function extractIterationMeta(tAttrs) {
var result = RE.exec(tAttrs.values);
if(!result) {
throw new Error('malformed values expression, use "itervar in list": ', tAttrs.values);
}
var cutoff = parseInt(tAttrs.cutoff || '5');
if(isNaN(cutoff)) {
throw new Error('malformed cutoff: ' + tAttrs.cutoff);
}
return {
varName: result[1],
list: result[2],
cutoff: cutoff
};
}
return {
scope: true, // investigate isolated scope too...
compile: function(tElem, tAttrs) {
var iterationMeta = extractIterationMeta(tAttrs);
var content = $compile(extractTrimmedContent(tElem));
tElem.empty();
return function link(scope, elem, attrs) {
var scopes = [];
scope.$watchCollection(
function() {
// this is (IMO) the only legit usage of scope.$parent:
// evaluating an expression we know is meant to run in our parent
return scope.$parent.$eval(iterationMeta.list);
},
function(newval, oldval) {
var i, item, childScope;
// this needs OPTIMIZING, the way ng-repeat does it (identities, track by); omitting for brevity
// if however the lists are not going to change, it is OK as it is
scopes.forEach(function(s) {
s.$destroy();
});
scopes.length = 0;
elem.empty();
for(i=0; i < newval.length && i < iterationMeta.cutoff; i++) {
childScope = scope.$new(false, scope);
childScope[iterationMeta.varName] = newval[i];
scopes.push(childScope);
content(childScope, function(clonedElement) {
if(i > 0) {
elem.append('<span class="sentence-sep">, </span>');
}
elem.append(clonedElement);
});
}
if(newval.length > iterationMeta.cutoff) {
// this too can be parametric, leaving for another time ;)
elem.append('<span class="sentence-more"> +' + (newval.length - iterationMeta.cutoff) + ' more</span>');
}
}
);
};
}
};
}]);
和提琴:https://jsfiddle.net/aza6u64p/
你可以使用ng-repeat =“article in articles”,它会创建必要的“句子”标签。 –
我知道我可以使用'ng-repeat'遍历所有标签。我的目标是通过显示“+5更多”来生成一个句子(即,与“,”和“和”),如果句子长于三个句子,则生成一个句子。我知道如何构建一个一次性版本 - 但希望能够重用指令,以便我可以在应用程序的多个区域使用它。或者我错过了什么? – Stussa
你在找什么对我来说听起来更像一个过滤器 – MilitelloVinx