2015-10-29 63 views
1

我在使用ng-repeat添加空白输入字段后遇到了一些问题。AngularJS - 无法清空输入字段

我的控制器看起来是这样的:

var SimpleController = function ($scope) { 
    $scope.rows = [{id: 'row1' }, {id: 'row2'}, {id: 'row3'}, {id: 'row4'}]; 

    $scope.addText = function() { 
     $scope.modelRow = "text"; 
    } 
    $scope.removeText = function() { 
     $scope.modelRow = " "; 
    } 
} 

我使用的是行阵列上NG-重复添加输入字段我所需要的量。例如,如果用户需要更多的字段,我有扩展数组的函数。

然后我有一个函数来清空输入和一个来填补他们,这就像预期的那样工作。但是,如果您自己在输入字段中输入内容,那么这两个函数都不会在该输入上起作用。

我的HTML:

<div ng-repeat="row in rows" > 
    <input ng-model="modelRow" type="text" name="text" /> 
</div> 

<button ng-click="addText()">Add text</button> 
<button ng-click="removeText()">Remove Text</button> 

我很新的角度,所以我可能失去了一些东西。希望有人能帮助我。

也做了一个jsfiddle来演示我的问题,它可以在这里找到:jsfiddle(尝试打字的东西,你会看到,功能不起作用)。

+0

您有多个modelRow,这是一个问题。 –

+0

我明白了。有什么好的解决方案来完成这项工作? – qua1ity

回答

3

只是阐述了以前的答案。这是您可以拥有的控制器。

var SimpleController = function ($scope) { 
    $scope.rows = [{id: 'row1', value: ''}, {id: 'row2', value: ''}, {id: 'row3', value: ''}, {id: 'row4', value: ''}]; 

    $scope.addText = function() { 
     for (var i in $scope.rows) { 
      $scope.rows[i].value = "text"; 
     } 
    }; 
    $scope.removeText = function() { 
     for (var i in $scope.rows) { 
      $scope.rows[i].value = ""; 
     } 
    } 
}; 

每一行模型应该有一个属性来存储用户输入的文本。函数addText()removeText()应该遍历行模型并修改value属性。

<div ng-repeat="row in rows"> 
    <input ng-model="row.value" type="text" name="text"/> 
</div> 

<button ng-click="addText()">Add text</button> 
<button ng-click="removeText()">Remove Text</button> 
+0

这似乎这样做。非常感谢! – qua1ity

2

HTML

<div ng-repeat="row in rows" > 
     <input ng-model="model.modelRow" type="text" name="text" /> 

    </div> 

<button ng-click="addText()">Add text</button> 
<button ng-click="removeText()">Remove Text</button> 

控制器

$scope.rows = [{id: 'row1' }, {id: 'row2'}, {id: 'row3'}, {id: 'row4'}]; 
    $scope.model={}; 
    $scope.model.modelRow=''; 
    $scope.addText = function() { 
     $scope.model.modelRow = "text"; 
    } 
    $scope.removeText = function() { 
     $scope.model.modelRow = " "; 
    } 

改变这样的代码将解决你的问题

编辑

在上面的代码,如果你在一个文本字段中输入的所有文本字段将充满了同样的内容,如果您使用单模式

它应该像

工作我的建议是改变ng-model="row.value"

HTML

<div ng-repeat="row in rows" > 
     <input ng-model="row.value" type="text" name="text" /> 
    </div> 

    <button ng-click="addText()">Add text</button> 
    <button ng-click="removeText()">Remove Text</button> 
    <!-- <pre>{{rows}}</pre> --> 

控制器

$scope.rows = [{id: 'row1' }, {id: 'row2'}, {id: 'row3'}, {id: 'row4'}]; 

    $scope.addText = function() { 
     for(var index in $scope.rows){ 
     $scope.rows[index].value="text"; 
     } 

    } 
    $scope.removeText = function() { 
     for(var index in $scope.rows){ 
     delete $scope.rows[index].value; 
     } 
    } 
+0

是的,我的意图是不要让文本字段填充相同的内容。他们应该是个人 – qua1ity

+0

检查编辑部分的代码,我认为这将满足您的要求 –