Search code examples
angularjsangularjs-ng-repeatselectedindex

dropdown selected value use only once on add button in angular js


Selected value from the drop down should be added when I click on add button, only once the value should be added to the result field. Some once can help me on this. below is code which i tried.

function ContactController($scope) {
 $scope.contacts = ["Apple"];
 $scope.curItem = [{
     id: "1",
     items: "Apple"
 }, {
     id: "2",
     items: "Orange"
 }, {
     id: "3",
     items: "Banana"
 }, {
     id: "4",
     items: "Apricot"
 }, {
     id: "5",
     items: "Asparagus"
 }, ];
 $scope.selectedItem = $scope.curItem[0];

}

View :

<table class="range-table" width="100%">
    <tr>
        <td>
            <input type="hidden">
            <button class="btn btn-link" value= "Save">
                <span class="glyphicon glyphicon-plus"></span>
            </button>
        </td>
        <td>
            <select required="" style="min-width:180px;"> </select>
        </td>
    </tr>
</table>

<table class="range-table" width="100%">
    <tr>
        <td ng-repeat="contact in contacts"> <td>{{ contact }}</td> 
    </tr>
</table>

Solution

  • HTML:

        <body ng-controller="MainCtrl">
    
    
            <table class="range-table" width="100%"> 
             <tr> 
                <td><input type="hidden"> <button class="btn btn-link" ng-click="save(selectedItem)">Save</button> </td> 
                <td><select ng-model="selectedItem" ng-options="i.items as i.items for i in curItem" ng-init="selectedItem=curItem[0].id"></select></td> </tr> 
    </table> 
    <table class="range-table" width="100%"> 
              <tr> 
              <tr ng-repeat="contact in contacts track by $index">
                 <td>{{ contact }}</td> 
              </tr>
     </table>
    
    </body>
    

    Javascript (your controller code):

    app.controller('MainCtrl', function($scope) {
      $scope.contacts = ["Apple"]; 
    
      $scope.curItem=[{id:"1",items:"Apple"}, {id:"2",items:"Orange"}, {id:"3",items:"Banana"}, {id:"4",items:"Apricot"}, {id:"5",items:"Asparagus"}]; 
      $scope.save=function(i){
        if ($scope.contacts.indexOf(i) <= -1){
         $scope.contacts.push(i);
        }
      };
    });
    

    Here is the working Plunker

    Edit: It seems that you want to add value only once. I've edited my answer and plunker.