2

In php usually we are doing name="skills[]" to get data from form as array but how to do this in angularjs? PHP example:

<input type="text" name="skills[]" />

I want to do the same in AngularJS but getting syntax error. I am trying like this:

My code:

<input type="text" name="skillname" required data-ng-model="c.skills[].skillname" class="small">
<input type="text" name="skillname" required data-ng-model="c.skills[].skiilname" class="small">

Need help. Thanks.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Harsh Doshi
  • 191
  • 11

2 Answers2

1

try this:

your controller is:

app.controller('MainCtrl', function($scope) {
   $scope.skills = [];
  $scope.formData={
   skillname:[]
      };
  });

and your html is:

<div ng-repeat="skill in skills">
<input type="text"  required ng-model="formData.skillname[$index]" ng-init="formData.skillname[$index]=skill.skillname" class="small">
  </div>

and without ng-repeat you can use this code:

<input type="text"  required ng-model="skillname[0]" ng-init="skillname[0]=skills[0].skillname" class="small">
<input type="text" required ng-model="skillname[1]" ng-init="skillname[1]=skills[1].skillname" class="small">
Mehran Hafizi
  • 2,392
  • 2
  • 12
  • 14
1

In angular, data rules your UI, not the other way around. You should have skills array in your controller

app.controller('MainCtrl', function($scope) {
  $scope.skills = [
    {},
    {},
    {}
  ];
});

which you'll feed to ng-repeat or something.

<div ng-repeat='skill in skills'>
  <input ng-model='skill.name' />
</div>

This way, adding new textfields on the page is as easy is pushing a new element to the array, $scope.skills.push({}). No need to create DOM elements or anything. This is the angular way.

Demo: http://plnkr.co/edit/Uqldnst3gnF07SJGV6Bn?p=preview

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367