Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 345
Alex Avatar asked Apr 07 '15 07:04

Alex


2 Answers

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"
like image 105
Deblaton Jean-Philippe Avatar answered Nov 16 '22 17:11

Deblaton Jean-Philippe


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.

like image 40
dting Avatar answered Nov 16 '22 19:11

dting