2

我在网上研究了如何创建一个额外的表单域。我使用的方法来自这个站点。

http://mrngoitall.net/blog/2013/10/02/adding-form-fields-dynamically-in-angularjs/

所以基本上我想要做的是输入数据。但我不知道某个人想输入多少数据点。所以我要启用它,这样我就可以让他们输入额外的点,如果他们希望。

我的标签中有这个:

  <script>
  function AngularCtrl($scope) {
  function Controller($scope) {
    $scope.master = {};

    $scope.update = function(user) {
      $scope.master = angular.copy(user);
    };

    $scope.reset = function() {
      $scope.user = angular.copy($scope.master);
    };

    $scope.reset();
  }

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

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


$scope.showAddChoice = function(choice) {
    return choice.id === $scope.choices[$scope.choices.length-1].id;
};



$scope.showChoiceLabel = function (choice) {
    return choice.id === $scope.choices[0].id;
}



}
</script>

然后我在我的标签中有这个:

<div class="form-group" ng-controller="Controller" data-ng-repeat="choice in choices">
  <form novalidate class="simple-form">
        Title of Chart: <input type="text" ng-model="chart.title" /><br />
        Series Name: <input type="text" ng-model="chart.series" /><br />
        Series Data: <input type="text" ng-model="series.data" /><br>

        <label for="choice" ng-show="showChoiceLabel(choice)">Choices</label>
        <button ng-show="showAddChoice(choice)" ng-
         click="addNewChoice()">Add another choice</button>
        <input type="text" ng-model="choice.name" name="" placeholder="Enter
         a new data point">         
        <br>
        <button ng-click="reset()">RESET</button>
        <button ng-click="update(user)">SAVE</button>
  </form>
</div>

如您所见,我拥有的是 4 个表单字段。我想要选择添加一个新的表单字段。我有按钮,但是当我单击按钮添加另一个表单字段时;这没用。它保持不变。

我想知道我的标签中的内容是否有点偏离。

感谢您的帮助。已经为此苦苦挣扎了好几个小时。

4

1 回答 1

0

扩展我的评论:

指令html:

<label for="choice" ng-show="showChoiceLabel(choice)">Choices</label>
<input type="text" ng-model="choice.name" name="" placeholder="Enter a new data point" />         
<br>
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">SAVE</button>

主要内容:

<div class="form-group" ng-controller="Controller">
  <form novalidate class="simple-form">
    Title of Chart: <input type="text" ng-model="chart.title" /><br />
    Series Name: <input type="text" ng-model="chart.series" /><br />
    Series Data: <input type="text" ng-model="series.data" /><br>
    <button ng-show="showAddChoice(choice)" ng-click="addNewChoice()">Add another choice</button>

    <div choice-editor ng-repeat="c in choices" choice="c"></div>
 </form>

我对指令的最佳实践非常模糊。有时我似乎在一个指令中混合了太多,即,我不确定你是否想要同一个元素上的ng-repeatandchoice属性......也许其他人可以改进这个答案。但这应该会给你一些关于如何进行的想法,希望如此。

于 2014-03-20T14:05:57.817 回答