ivan ivan - 2 months ago 8
AngularJS Question

Not able to get selected element in select element

I have an API which returns a JSON element in this format

{
"XYZ": ["xyz","abc"],
"ABC": ["cde","abc"],
"CDE": ["bla","blla"]
}


I have to add those elements in dropdown, for that html code is

<select class="ui search dropdown selection" ng-options="v for (v,k) in <API returns JSon>" style ="select:invalid { color: gray; }" ng-model="xyz">
<option value="" disabled selected hidden>Select Element</option>
</select>
<button type="button" class="btn btn-primary" ng-click='saveData(xyz)'>Save</button>


And my directive is

angular.module('member').directive('memberDirective',function(){
templateUrl: "../../XYZ/xyz.html",
controller: 'appConttroller',
link: function($scope){
$scope.saveData = function(data){
console.log(data);
}
}
});


Now the main problem is even if user selects any one of the value from dropdown and clicks Save button, in console log I can see its corresponding value.

Like for example if user selects XYZ and click Save button, in console log I can see ["xyz","abc"]. But I want value whatever user has selected, not its corresponding value.
So can anyone suggest how to achieve this? For all other select elements in my Program I get value from ng-model only don't know why here it's going wrong?

Answer

You should use the select as syntax from the ngOptions directive like so:

<select class="ui search dropdown selection" ng-options="v as v for (v,k) in json" style ="select:invalid { color: gray; }" ng-model="xyz">
    <option value="" disabled selected hidden >Select Element</option>
</select>

(function() {

  angular.module('MyApp', [])
    .controller('MyController', MyController);

  MyController.$inject = ['$scope']

  function MyController($scope) {

    $scope.json = {
      "XYZ": ["xyz", "abc"],
      "ABC": ["cde", "abc"],
      "CDE": ["bla", "blla"]
    }
    
    $scope.saveData=function(data){
      console.log(data);
    }

  }

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="MyApp">

  <div ng-controller="MyController">


    <select class="ui search dropdown selection" ng-options="v as v for (v,k) in json" style="select:invalid { color: gray; }" ng-model="xyz">
      <option value="" disabled selected hidden>Select Element</option>
    </select>
    
    <p>Value of ngModel: {{xyz}}</p>
    
    <button type="button" class="btn btn-primary" ng-click='saveData(xyz)'>Save</button>


  </div>


</div>

Comments