Nivin Nivin - 1 month ago 12
AngularJS Question

How to take value(index) of inputbox in angularjs

Angularjs

<tr ng-repeat="advLi in media">
<td>
<input style="display:none;" type="text" style="width:35px;" class="form-control" name="mediaindex" value="{{$index+1}}" ng-model="advLi.media_order">
</td>
<td>{{advLi.media_name}}</td>
</tr>


when I submit form, the "media" list not showing media_order, only showing media_name. How can I get media_order value in controller.

Answer

If I understood your problem correctly you want to display items index value as sequence number in the text box and user can change it later to rearrange the order.

Then I've added ng-init="advLi.media_order = $index + 1" in your input tag so that when ever a new DOM element is created in ng-repeat then we intialise the ng-model value with index + 1 which will display the sequence number on text box.I've also removed the style which hides your text box.

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

app.controller('MainCtrl', function($scope) {
  
  $scope.media =[{media_name:"Still"},{media_name:"Gangsta"},{media_name:"Weed it out"}];
  
  $scope.submit = function (){
    
    angular.forEach($scope.media,function(val,key){
      
      console.log(val.media_order + ' - '+ val.media_name);
      });
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="app" ng-controller="MainCtrl">
  <table> 
    <tr ng-repeat="advLi in media">
    <td>
        <input  type="text" style="width:35px;" class="form-control" name="mediaindex" value="{{$index+1}}" ng-init="advLi.media_order = $index + 1" ng-model="advLi.media_order">
    </td>
      <td>{{$index +1}} </td>
    <td>{{advLi.media_name}}</td>
      <td>{{advLi.media_order}}</td>
</tr>
    </table>
  <button ng-click="submit()">Submit </button>
  </body>

Comments