viiq
viiq

Reputation: 35

How to retrieve text from several input fields with same ng-model in Angular

I have a page that displays an input field after the user clicks a button. If the user clicks the same button several times, the application will spawn the same input field several times. Likewise, there is a button to remove the last input field that was added.

After the user has spawned and filled out as many input fields as they want, I want the user to be able to click a button whose action will then be to gather all the information from the input fields, and do a console.log() of all that information. How would I go about doing this in Angular.js?

Here is the way I am currently doing the part where I add/remove input fields, and my attempt at gathering the data from the view.

<div ng-app="" ng-controller="myController">
    <button ng-click="add()">Click Me to Add!</button>
    <button ng-click="rem()">Click Me to Remove!</button>
    <div ng-repeat="x in obj">
        <label>Input 1</label><input type="text" ng-model="thing">
    </div>
    <button ng-click="display()">display</button>
</div>
<script>
function myController($scope){
    $scope.obj = [];
    $scope.count = 0;
    $scope.add = function(){
        $scope.count = $scope.count + 1;
        $scope.obj.push({lett: $scope.count});
    };
    $scope.rem = function(){
        $scope.count = $scope.count - 1;
        $scope.obj.pop();
    };
    $scope.display = function(){
        console.log($scope.thing);
    };
}
</script> 

The part where I do ng-model="thing" is my attempt to bind the data from the view, to the application. $scope.display is the function that is supposed to do the displaying.

Thanks in advance for your responses!

Upvotes: 1

Views: 314

Answers (1)

renlo
renlo

Reputation: 21

I rewrote some of your code to make it work:

    <div ng-app="" ng-controller="myController">
        <button ng-click="add()">Click Me to Add!</button>
        <button ng-click="rem()">Click Me to Remove!</button>
        <div ng-repeat="input in inputs track by $index">
            <label>Input {{ $index }}</label>
            <input type="text" ng-model="input.value" />
        </div>
        <button ng-click="display()">display</button>
    </div>
    <script>
    function myController($scope){
        $scope.inputs = [];
        $scope.add = function(){
            $scope.inputs.push({'value':''});
        };
        $scope.rem = function(){
            $scope.inputs.pop();
        };
        $scope.display = function(){
            console.log($scope.inputs);
        };
    }
    </script>

You can see the fiddle here: http://jsfiddle.net/K38GC/

To get the display the way you want it you can edit the $scope.display function to fit whatever you'd like. Let me know if you have any questions.

Upvotes: 1

Related Questions