编辑输入名称值

时间:2017-04-10 08:04:00

标签: angularjs

我正在使用AngularJS动态添加表单元素,如下所示,它工作得很好。

但有时候,用户需要更改占位符的值,并用他选择的值替换它,我不知道它是否可能?

这是我的HTML

<div ng-app="angularjs-starter" ng-controller="MainCtrl">
   <fieldset data-ng-repeat="choice in choices">
   <div class="col-xs-3">
       <div class="input-group">
           <span class="input-group-addon">Tr.</span>
           <input id="tr-dpa" class="form-control" placeholder="Enter mobile number">

           <button class="remove"  ng-click="removeChoice()">-</button>
       </div>
   </div>
   </fieldset>

   <div class="form-group">
       <div class="col-xs-5 col-xs-offset-1">
         <button type="submit" class="add" ng-click="addNewChoice()">
         +
         </button>
       </div>
   </div>
</div>

我的剧本,

var app = angular.module('angularjs-starter', []);

  app.controller('MainCtrl', function($scope) {

  $scope.choices = [{id: 'choice1'}];

  $scope.addNewChoice = function() {
    var newItemNo = $scope.choices.length+1;
    $scope.choices.push({'id':'choice'+newItemNo});
  };



  $scope.removeChoice = function() {
    var lastItem = $scope.choices.length-1;
    $scope.choices.splice(lastItem);
  };

});

jsfiddle

1 个答案:

答案 0 :(得分:2)

您应该拥有这样的choices数组:

$scope.choices = [{
    id: 'choice1',
    placeholder: 'Enter Mobile Number'
  }];

而且,在ng-repeat内,

<input id="tr-dpa" class="form-control" placeholder="{{choice.placeholder}}">

现在,当您添加新输入时,请求占位符并将其与id一起推送。

$scope.addNewChoice = function() {
    var newItemNo = $scope.choices.length + 1;
    $scope.choices.push({
      'id': 'choice' + newItemNo,
      placeholder: $scope.placeholder
    });
    $scope.placeholder = "sample placeholder"
  };

而且,$scope.placeholder将是HTML格式,

 <input type="text" value="sample placeholder" ng-model="placeholder">
 <button type="submit" class="add" ng-click="addNewChoice()">
   +
 </button>

working example