Javascript AngularJS 在范围内获取所选项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29486250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS get selected item in scope
提问by Alex
I'm developing app with Ionic and AngularJS. Can't figure how to get value of selected option
我正在使用 Ionic 和 AngularJS 开发应用程序。无法弄清楚如何获取所选选项的值
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(obj)总是返回先前选择的值
console.log(countSelector)Always return default value (if set) or undefined
console.log(countSelector)总是返回默认值(如果设置)或未定义
采纳答案by Deblaton Jean-Philippe
When you do select ng-model="countSelector", you are binding your select to $scope.countSelector
当您这样做时select ng-model="countSelector",您将选择绑定到$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 :
根据您的要求,您可能希望直接拥有 $scope.countSelector 中的值。为此,您可以将 ng-options 调整为以下内容:
ng-options="opt.id as opt.label for opt in options"
回答by DTing
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:
您将 countSelector 的字符串版本传递给 ng-change 函数。如果你看一下html,它看起来像这样:
<select ng-model="countSelector"
ng-change="changeCount('{"id":1,"label":"30","value":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:
从技术上讲,您可以通过不使用表达式将 countSelector 传递到您的函数中:
<select ng-model="countSelector" ng-change="changeCount(countSelector)" ng-options="opt as opt.label for opt in options">
As @Deblaton Jean-Philippe answer explains, you have access to that via the scope so it's not really needed.
正如@Deblaton Jean-Philippe 的回答所解释的那样,您可以通过范围访问它,因此它并不是真正需要的。

