简体   繁体   中英

Getting selected values from dropdown options inside nested ng-repeat in AngularJS

I'm trying to access value of selected value of dropdown options. But problem is that i already have ng-repeat as parent div and inside that options in dropdowns are also using ng-repeat. So basically its nested ng-repeat.

So I'm not able to access selected values.

jsFiddle

<div ng-controller="csrClrt">
<div  ng:repeat="item in items track by $index">

  <md-list one class="md-accordion">
            <md-input-container>
                   <label>Face Style:</label>
                  <md-select ng-model="style">
                   <md-option ng-value="user.name" ng:repeat="user in styles">{{user.name}}</md-option>
                  </md-select>
          </md-input-container>  
   </md-list>
</div>
<div>
<input type="button" value="get selected value" ng-click="getvalue()"/>
</div>

                    <p>
                    if i ttry out of parent ng repeat
                    </p>
                     <md-input-container>
                   <label>Face Style:</label>
                  <md-select ng-model="style">
                   <md-option ng-value="user.name" ng:repeat="user in styles">{{user.name}}</md-option>
                  </md-select>
          </md-input-container>
                              <div>

<input type="button" value="get selected value" ng-click="getvalue()"/>
                              </div>

                                 </div>

AngularJS

angular.module('MyApp', ['ngMaterial'])
.controller('csrClrt', function ($scope) {
     $scope.items=["0"];
     stylesdata=[{name:"a"},{name:"b"},{name:"c"}];
     var style=[];
     for(var i=0;i<stylesdata.length;i++)
     {
       style.push({
        name:stylesdata[i].name
       })
     }
     $scope.styles=style;
     $scope.getvalue=function()
     {

       alert($scope.style);
     }
})

Repeat isolates the scope if you want to do it without an isolated scope then bind the variables as an object and not an independent variable like this

<md-select ng-model="a.style">

and access it as

 alert($scope.a.style);

see fiddle https://jsfiddle.net/44a0thqt/1/

You had same model name for the both dropdowns ng-model="style"> . that is a problem


You should provide spate name to the ng-model directive

Update

Also your first select tag inside of the ng-repeat So it will be create multiple select tag's. This time you should pass the index and get the data.

So kindly change your first drodown model name to ng-model="item.style"> . So now you can get the value by using the index count as like $scope.items[indexNumber].style

See the demo : https://jsfiddle.net/44a0thqt/3/

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