techie20
techie20

Reputation: 508

How to have different values in dynamically added array

I have one form I am adding some fields say name,age,sex through that form

<html>
<body>
  <form>
    <input type="text" ng-model="name">
    <input type="text" ng-model="age">
    <input type="text" ng-model="sex">
    <input type="button" value="add" ng-click="addToArray()">
  </form>
  <div ng-repeat="item in formdata">
    <input type="text" ng-model="item.name">
    <input type="text" ng-model="item.age">
    <input type="text" ng-model="item.sex">
  </div>
</body>
</html>

In Controller

app.controller('ExampleCtrl', function() {
  var formdata = [];

  $scope.addToArray = function() {
    var temp = {
      name: $scope.name,
      age: $scope.age,
      sex: $scope.sex
    }
    formdata.push(temp);
  }
});

Now the problem is when I add object to formdata array and display it with ng-repeat it shows same data for each object.

For ex:

if I enter "John",23,"Male" & "Medona",34,"Female"

it shows "Medona",34,"Female" two times

I want each object to have different property value.

Upvotes: 0

Views: 74

Answers (2)

rkalita
rkalita

Reputation: 575

You should use the $scope in your controller like

app.controller('ExampleCtrl',function($scope){
    $scope.formdata=[];

    $scope.addToArray=function(){
        var temp={
            name:$scope.name,
            age:$scope.age,
            sex:$scope.sex
        }
        $scope.formdata.push(temp);
    };
});

Or you can use 'this' and the name of your controller or alias.

    <html>
        <body ng-controller="ExampleCtrl as ctrl">
            <form>
                <input type="text" ng-model="name">
                <input type="text" ng-model="age">
                <input type="text" ng-model="sex">
                <input type="button" value="add" ng-click="ctrl.addToArray()">
            </form>
           <div ng-repeat="item in formdata">
               <input type="text" ng-model="item.name">
               <input type="text" ng-model="item.age">
               <input type="text" ng-model="item.sex">
           </div>
        </body>
    </html>


app.controller('ExampleCtrl',function(){
    var self = this;
    self.formdata=[];

    self.addToArray=function(){
        var temp={
            name:Petter,
            age:25,
            sex:'Male'
        }
        self.formdata.push(temp);
    };
});

Here is the Plunker

Upvotes: 2

zamarrowski
zamarrowski

Reputation: 483

Update var formdata to $scope.formdata:

$scope.formdata = [];

$scope.addToArray = function() {
  var temp = {
    name: $scope.name,
    age: $scope.age,
    sex: $scope.sex
  }
  $scope.formdata.push(temp);
}

Upvotes: 2

Related Questions