我有以下指令。我通常不喜欢发布太多代码,以便那些试图回答问题的人可以专注于重要部分,但我不确定我在这里做错了什么,所以我必须这样做。
这是一个应该重复元素的所有子元素的指令。初始渲染有效,但是当我修改列表时,事情变得一团糟。有关用法示例,请参阅此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
})