AngularJS获取范围中的选定项目

AngularJS get selected item in scope

本文关键字:项目 获取 范围 AngularJS      更新时间:2023-09-26

我正在用Ionic和AngularJS开发应用程序。无法计算如何获得所选选项的值

控制器

.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);
    };
    ...
})

模板

<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)始终返回以前选择的值

console.log(countSelector)始终返回默认值(如果设置)或未定义的

执行select ng-model="countSelector"时,您将选择绑定到$scope.countSelector

因此,在您的控制器中,如果您想访问您选择的值,请使用以下方法:

$scope.countSelector

编辑:

根据您的要求,您可能希望直接在$scope.countSelector中设置值。为此,您可以根据以下内容调整ng选项:

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

您正在将countSelector的字符串版本传递给ng-change函数。如果你看一下html,它看起来像这样:

<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">

从技术上讲,您可以通过不使用表达式将countSelector传递到函数中:

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

http://jsfiddle.net/r2zgmgq1/

正如@Deblaton Jean-Philippe answer所解释的,你可以通过作用域访问它,所以实际上并不需要它。