简体   繁体   中英

Add items to list in angular

I have the following to create a job with a position and multiple requirements Plunker example :

<div ng-controller="MainCtrl as vm">      
  <div>Position: <span data-ng-bind="vm.job.position"></span></div>      
  <br/>      
  <form name="form" data-ng-submit="vm.create(job)">        
    <label for="position">Enter the Position</label>
    <input id="position" name="vm.job.position" type="text" data-ng-model="vm.job.position" />
    <div>
      <br/>
      Requirements:
      <br/>
      <ul>
        <li data-ng-repeat="r in vm.job.requirements">{{r.name}}</li>
      </ul>
      <input id="name" name="requirement.name" type="text" data-ng-model="requirement.name" />
      <input type="button" value="Add Requirement" class="button" data-ng-click="vm.addRequirement(requirement)"/>          
    </div>        
    <br/><br/>                
    <button>Create Job</button>              
  </form>            
</div>    

the controller

var app = angular.module('plunker', []);

  app.controller('MainCtrl', function($scope) {
    var vm = this;  
    vm.job = { position: '', requirements: [] };

    vm.create = function (job) {      
      alert("job created");    
    }

    vm.addRequirement = function (requirement) {
      vm.job.requirements.push(requirement);
    }  

});

When I add a requirement I see it on the list but when I try to add a new one, the one that is already in the list start to change. I do not want that. I want to add a new one to the list.

Finally, when I submit the form using "Create Job" is where I will send all the Job data to the API.

The problem is with your addRequirement function, because you are adding the same object to the list (and that's the reason your item changes the name when you edit the input box).

To make your example work as intended you should push a clone of the requirement object (see documentation ).

 vm.addRequirement = function (requirement) {
   vm.job.requirements.push( angular.copy(requirement) );
 }  

The easiest way to do this, is simply use ng-model on the input that you would like to append to your list. Then you can easily access it from the controller.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  var vm = this;
  vm.job = { position: '', requirements: [] };

  function create(job) {
    alert("job created");
  }

  function addRequirement() {
    vm.job.requirements.push(vm.currentRequirement);
  }

  vm.create = create;
  vm.addRequirement = addRequirement;

});

and in the html:

 <input type="button" value="Add Requirement" ng-click="vm.addRequirement()"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM