【发布时间】:2015-12-20 09:54:27
【问题描述】:
我已经使用动态生成的 ng-model 名称动态创建了元素,例如:
以下是伪代码。
$scope.arr = [];
//html
<input type="button" ng-click="addNewVariable()">
$scope.addNewVariable = function() {
$scope.arr.push([]);
//some code that results in DOM inputs that follow
}
//dynamically created dom html
<input type="text" ng-model="myVariableName1" value="">
<input type="text" ng-model="myVariableName2" value="">
<input type="text" ng-model="myVariableName3" value="">
现在在屏幕上,我在输入中输入一些数据:
<input type="text" ng-model="myVariableName1" value="a">
<input type="text" ng-model="myVariableName2" value="b">
<input type="text" ng-model="myVariableName3" value="c">
此时我有:
//I intentionally do not save values to array,
//but save them to dynamically created scope variables
$scope.arr = [[],[],[]];//i do need this structure for other purposes.
并且(很可能)在内存/作用域中:
$scope.myVariableName1 = "a";
$scope.myVariableName2 = "b";
$scope.myVariableName3 = "c";
现在我使用拼接函数从数组中删除这些输入元素:
$scope.removeArrayElements = function(removeIndex) {
$scope.arr.splice(removeIndex, 1);
//the same code as above earlier,
//but this time it removes(automatically) the inputs from Dom
}
//dynamically removed dom html
(Deleted myVariableName1 - no longer in Dom.)
(Deleted myVariableName2 - no longer in Dom.)
(Deleted myVariableName3 - no longer in Dom.)
现在我再次创建这些输入。
但生成的输入确实保留旧值,例如。
//dynamically created new dom html
<input type="text" ng-model="myVariableName1" value="a">
<input type="text" ng-model="myVariableName2" value="b">
<input type="text" ng-model="myVariableName3" value="c">
我期望的地方:
//dynamically created new dom html
<input type="text" ng-model="myVariableName1" value="">(empty value)
<input type="text" ng-model="myVariableName2" value="">(empty value)
<input type="text" ng-model="myVariableName3" value="">(empty value)
所以问题是 - 如何删除可能保存在内存/作用域中的动态创建的 ng-models/ng-data-bindings?
类似于eval() 函数:
$scope.removeArrayElements = function(removeIndex, removeMyNgModelName) {
$scope.arr.splice(removeIndex, 1);
//the same code as above earlier,
//but this time it removes(automatically) the inputs from Dom
//this is what my question is all about!
$scope.{removeMyNgModelName}.remove();//myVariableName1, myVariableName2, myVariableName3
}
【问题讨论】:
标签: angularjs dynamic model ng-bind