2014-02-27 45 views
13

我试图动态添加输入表单,当“新项目”被点击。但并不知道如何在js部分编写代码。任何想法?如何动态添加输入表单?

这里是我的代码:

<!doctype html> 
<html ng-app> 
    <head> 
    <title>Angular - My Notes</title> 
    <link rel="stylesheet" type="text/css" href="css/index.css"> 

    <body> 
    <h1>My Notes</h1> 
    <div ng-controller="Note"> 
     <input type="text" placeholder="Question"> 
     <input ng-class="{'blockInput': !inlineChecked}" type="text" placeholder="enter text..."> 
     <input type="checkbox" name="check" value="inline" ng-model="inlineChecked"> Inline 
     <br> 
     <button ng-click="add()">New Item</button> 
    </div> 

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script> 
    <script type="text/javascript"> 

     var Note = function($scope){ 
     // create a variable contain new input forms?? 
     } 


    </script> 
    </body> 
</html> 

回答

33

使用数组和ngRepeat ...

<!doctype html> 
<html ng-app> 
    <head> 
    <title>Angular - My Notes</title> 

    <body> 
    <h1>My Notes</h1> 
    <div ng-controller="Note"> 
     <div ng-repeat="item in items"> 
     <input type="text" placeholder="{{item.questionPlaceholder}}" ng-model="item.question"> 
     <input ng-class="{'blockInput': !item.inlineChecked}" type="text" placeholder="enter text..." ng-model="item.text"> 
     <input type="checkbox" name="check" value="inline" ng-model="item.inlineChecked"> Inline 
     </div> 
     <button ng-click="add()">New Item</button> 
    </div> 

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script> 
    <script type="text/javascript"> 

     var Note = function($scope){ 
     $scope.items = []; 

     $scope.add = function() { 
      $scope.items.push({ 
      inlineChecked: false, 
      question: "", 
      questionPlaceholder: "foo", 
      text: "" 
      }); 
     }; 
     } 


    </script> 
    </body> 
</html> 

JsBin ... http://jsbin.com/fusapojo/4/edit?html,output

+0

需要添加一点点(ng-model on inputs)。例如,在你jsBin中添加'{{items | json}}'并填写一些表单,你会看到:) – jnthnjns

+0

@Asok如何通过angularjs编辑占位符值? – Jusleong

+0

@Asok谢谢。我不想添加比原来需要的更多。现在更新。 :) –

3

HTML:

<div ng-repeat="flavour in flavours" class="form-group"> 
    <label class="col-sm-1 control-label">Name</label> 
    <div class="col-sm-2"> 
     <div class="input-group"> 
       <input type="text" class="form-control" placeholder="" ng-model="flavour.name"> 
     </div>     
    </div> 
</div> 

JS : $ scope.flavours = [];

$scope.addFlavour = function() { 
    $scope.flavours.push({ 
     name: "", 
     pg: 100, 
     vg: 0, 
     quantity: 5.0 
    }); 
}