在Angular.js中更改具有相同名称的输入文本的值

时间:2016-12-28 16:08:29

标签: javascript angularjs

我想在单击文本字段时将其值更改为2。

<input type='text' name='field[]' ng-model='field' ng-click='changeval()'>
<input type='text' name='field[]' ng-model='field' ng-click='changeval()'>
<input type='text' name='field[]' ng-model='field' ng-click='changeval()'>
<input type='text' name='field[]' ng-model='field' ng-click='changeval()'>

$scope.changeval=function(){
  //set value of input text for 2    
}

http://fiddle.jshell.net/0w36h8zm/

2 个答案:

答案 0 :(得分:1)

如果您有很多字段

,请使用数组和索引作为参数
<input type='text' name='field[]' ng-model='field[0]' ng-click='changeval(0)'>
<input type='text' name='field[]' ng-model='field[1]' ng-click='changeval(1)'>
<input type='text' name='field[]' ng-model='field[2]' ng-click='changeval(2)'>
<input type='text' name='field[]' ng-model='field[3]' ng-click='changeval(3)'>

<强> JS

angular.module("myApp", ['ui.bootstrap'])
.controller("MyCtrl", function($scope, $modal) {

    $scope.field = [];
        $scope.changeval=function(index){
        //change the val for 2;
      $scope.field[index]=2;
    };


});

http://fiddle.jshell.net/0w36h8zm/9/

答案 1 :(得分:0)

如果要更改所有文本字段中的值,请执行以下操作:

angular.module("myApp", ['ui.bootstrap'])
.controller("MyCtrl", function($scope, $modal) {
    $scope.changeval=function(){
    $scope.field=2;
}

});

如果要更改单击的文本字段的值,请执行以下操作:

     <input type='text' name='field[]' ng-model='field1' ng-click='changeval1()'>
      <input type='text' name='field[]' ng-model='field2' ng-click='changeval2()'>
           <input type='text' name='field[]' ng-model='field3' ng-click='changeval3()'>
                <input type='text' name='field[]' ng-model='field4' ng-click='changeval4()'>




     angular.module("myApp", ['ui.bootstrap'])
.controller("MyCtrl", function($scope, $modal) {
$scope.changeval1=function(){
$scope.field1=2;
 }

$scope.changeval2=function(){
$scope.field2=2;
}

$scope.changeval3=function(){
$scope.field3=2;
}


$scope.changeval4=function(){
$scope.field4=2;
}
 });

http://fiddle.jshell.net/0w36h8zm/3/