I am creating options with an ng-repeat and on ng-change I would like to call a controller function and pass the option value and label. I have tried to also create the options using ng-options but have fallen into a rat hole of ng-repeat filters that did not help.
I can pass the ng-model to the function and that gets me the value, but not both the value and label.
Here is the code I have that represents what I'd like do but is obviously not functional because the ng-change function call is outside the ng-repeat.
diskSizes = [
{
"label": "100GB",
"value": 100
},
{
"label": "250GB",
"value": 250
},
{
"label": "500GB",
"value": 500
},
{
"label": "1TB",
"value": 1000
},
{
"label": "1.5TB",
"value": 1500
}
]
HTML
<td >
<select ng-model="disk_size" ng-change="saveData(value,label)">
<option ng-repeat="item in diskSizes" value={{item.value}}>{{item.label}}</option>
</select>
</td>
CodePudding user response:
Typically with angularJS, the HTML just reflects the data structure, and it's the data structure where you probably should grab the label value.
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.diskSizes = [{
"label": "100GB",
"value": 100
},
{
"label": "250GB",
"value": 250
},
{
"label": "500GB",
"value": 500
},
{
"label": "1TB",
"value": 1000
},
{
"label": "1.5TB",
"value": 1500
}
]
$scope.saveData = function() {
let val = $scope.disk_size;
let lab = $scope.diskSizes.filter(f => f.value == val)[0].label;
console.log(lab, val)
}
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="disk_size" ng-change="saveData()">
<option ng-repeat="item in diskSizes" value={{item.value}}>{{item.label}}</option>
</select>
</div>