次のディレクティブがあります。私は通常、質問に答えようとしている人が重要な部分に集中できるように、あまりにも多くのコードを投稿するのは好きではありませんが、ここで何が間違っているのかわからないので、そうしなければなりません.
これは、要素のすべての子を繰り返すディレクティブです。最初のレンダリングは機能しますが、リストを変更するとめちゃくちゃになります。使用例については、このjsFiddleを参照してください。アイテムを削除して、何が問題なのかを確認してください。
bigblind = window.bigblind || angular.module("bigblind",[]);
bigblind.directive("repeatInside", function(){
var makeChildScope = function(scope, index, key, val, keyIdentifier, valIdentifier){
childScope = scope.$new();
childScope.index = index
if (keyIdentifier) childScope[keyIdentifier] = index;
childScope[valIdentifier] = val;
childScope.first = (index == 0);
return childScope
};
var ddo = {
transclude:true,
compile: function(element, attrs, transclude){
return function($scope, $element, $attr){
var expression = $attr.repeatInside;
var match = expression.match(/^\s*(.+)\s+in\s+(.*?)$/)
var lhs, rhs
var keyIdentifier, valIdentifier, hashFnLocals = {};
if(!match){
throw "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got " + expression;
}
lhs = match[1];
rhs = match[2];
match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
if (!match) {
throw "bad left hand side in loop";
}
valIdentifier = match[3] || match[1];
keyIdentifier = match[2];
$scope.$watch(rhs, function(newval, oldval) {
var childScope, index = 0
for (var child in $element.children){
child.remove();
}
if (angular.isArray(newval)){
for (index=0; index<newval.length; index++) {
childScope = makeChildScope($scope, index, index, newval[index], keyIdentifier, valIdentifier);
transclude(childScope, function(clone){
clone.scope = childScope;
$element.append(clone);
});
}
}else{
for (key in newval){
if (newval.hasOwnProperty(key) && !key[0] == "$") {
childScope = makeChildScope($scope, index, key, newval[key], keyIdentifier, valIdentifier);
index += 1;
transclude(childScope, function(clone){
clone.scope = childScope;
$element.append(clone);
});
}
}
}
}, true);
}
}
};
return ddo
})