2017-04-10 190 views
0

我使用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

+0

你要動態改變的佔位符名稱? –

+0

請嘗試像這樣'placeholder =「{{your placeholder}}」' –

+0

@RameshRajendran是的,我希望用戶可以更改佔位符或輸入的名稱 –

回答

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

+0

哦謝謝! 這工作正常,我會接受你的回答 –

+0

@NabilCHOUKRI很高興我可以幫助! :) – tanmay