迭代和提供動態內容定義的數量是與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