AngularJS gets the selected item in scope

I am developing an application with Ionic and AngularJS. Unable to figure out how to get the value of the selected option.

controller

.controller('TestCtrl', function($scope, $options) { $scope.options = [ { id: 0, label: '15', value: 15 }, { id: 1, label: '30', value: 30 }, { id: 2, label: '60', value: 60 } ] $scope.countSelector = $scope.options[0]; $scope.changeCount = function(obj){ obj = JSON.parse(obj); console.log(obj) console.log(countSelector) $options.set('productCountPerPageValue', obj.value); $options.set('productCountPerPage', obj.id); }; ... }) 

Template

 <ion-list ng-controller="TestCtrl"> <label class="item item-input item-select"> <div class="input-label"> {{countSelector}} </div> <select ng-model="countSelector" ng-change="changeCount('{{countSelector}}')" ng-options="opt as opt.label for opt in options"> </select> </label> </ion-list> 

console.log (obj) Always return the previously selected value

console.log (countSelector) Always return the default value (if set) or undefined

+6
source share
2 answers

When you do select ng-model="countSelector" , you bind your selection to $scope.countSelector

So, inside your controller, if you want to access the value you selected, you use the following:

 $scope.countSelector 

edit:

according to your requirements, you can have a direct value inside $ scope.countSelector. To do this, you can adapt the ng options to the following:

 ng-options="opt.id as opt.label for opt in options" 
+5
source

You pass the string version of your counter to the ng-change function. If you look at html, it looks like this:

 <select ng-model="countSelector" ng-change="changeCount('{&quot;id&quot;:1,&quot;label&quot;:&quot;30&quot;,&quot;value&quot;:30}')" ng-options="opt as opt.label for opt in options" class="ng-valid ng-dirty"> 

You can technically pass countSelector into your function without using an expression:

 <select ng-model="countSelector" ng-change="changeCount(countSelector)" ng-options="opt as opt.label for opt in options"> 

http://jsfiddle.net/r2zgmgq1/

As @Deblaton Jean-Philippe's answer explains, you have access to this through scope, so it is not needed.

+2
source

Source: https://habr.com/ru/post/984772/


All Articles