我有以下指令。我通常不喜歡張貼太多的代碼,以便那些試圖回答問題的人可以關注重要的部分,但我不確定我在這裏做錯了什麼,所以我必須這樣做。清除angularjs指令中的DOM節點
這是一個指令,應該重複元素的所有孩子。最初的渲染工作,但當我修改列表,事情變得混亂。有關使用示例,請參見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
})
刪除它們有一個很奇怪在這裏,我不能換我的頭周圍...我要發佈一個答案,而不是評論,所以我可以更好地格式化我的代碼 – tnunamak