AngularJs删除动态创建的ng-models / ng-bind

时间:2015-12-20 09:54:27

标签: angularjs dynamic model ng-bind

我使用动态生成的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";

现在我使用splice函数从数组中删除这些输入元素:

$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.)

现在我再次创建这些输入。

但是结果输入要保持OLD值,比如。

//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-binding?

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
}

1 个答案:

答案 0 :(得分:0)

您需要使用bracket notation来定位具有变量名称的属性:

$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

    delete $scope['myVariableName' + removeIndex]; //myVariableName1, myVariableName2, myVariableName3
}