Alex
Alex

Reputation: 873

AngularJS get selected item in scope

I'm developing app with Ionic and AngularJS. Can't figure how to get value of 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 previously selected value

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

Upvotes: 8

Views: 30003

Answers (2)

dting
dting

Reputation: 39287

You are passing in the string version of your countSelector to your ng-change function. If you look at the 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 technically can pass the countSelector into your function by not 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 answer explains, you have access to that via the scope so it's not really needed.

Upvotes: 3

Deblaton Jean-Philippe
Deblaton Jean-Philippe

Reputation: 11388

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

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

$scope.countSelector

edit :

according to your requirements, you might want to have directly the value inside $scope.countSelector. To do so, you can adapt your ng-options to the following :

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

Upvotes: 5

Related Questions