如何获取下拉列表框选中的文本值,并找到调用函数的来源(调用函数的位置)。
<div ng-controller="cntrl">
<select id="dflfnt" ng-change="opfun()" ng-model='mddl1' ng-options='option.value as option.name for option in ddl1Options.data'>
</select>
<select id="3dfnt" ng-model='mddl2' ng-change="opfun()" ng-options="option.value as option.name for option in ddl2option.data">
</select>
</div>
<script>
function cntrl($scope)
{
$scope.ddl1Options={
data:[
{value:"Georgia, serif",name:"Style 1"},
{value:"'Palatino Linotype', 'Book Antiqua', Palatino, serif",name:"Style 2"}
]};
$scope.ddl2option={
data:[
{value:"font-effect-anaglyph",name:"anaglyph"},
{value:"font-effect-brick-sign",name:"brick-sign"},
{value:"font-effect-canvas-print",name:"canvas-print"},
{value:"font-effect-crackle",name:"crackle"}
]};
$scope.opfun=function(){
alert($scope.mddl1); // Here I can get the value only
}
}
</script>
在上面我想知道 opfun()的触发位置,并获取下拉列表框的选定文本。
我试图获得如下文字。
alert($scope.ddl2option.data[0].name);
但显示总是选择索引。
答案 0 :(得分:1)
不完全确定您的目标,但请尝试从option.value
指令中删除ng-options
。
这就是你的目标......
另外,你应该考虑将你的变量名更改为更具可读性的名称,因为它很难弄清楚这些神秘的变量名称是怎么回事。
<强> app.js 强>
var app = angular.module('plunker', []);
app.controller('cntrl', cntrl);
function cntrl($scope){
$scope.ddl1Options = {
data:[
{value:"Georgia, serif", name:"Style 1"},
{value:"'Palatino Linotype', 'Book Antiqua', Palatino, serif", name:"Style 2"}
]
};
$scope.mddl1 = $scope.ddl1Options.data[0];
$scope.ddl2option = {
data:[
{value:"font-effect-anaglyph",name:"anaglyph"},
{value:"font-effect-brick-sign",name:"brick-sign"},
{value:"font-effect-canvas-print",name:"canvas-print"},
{value:"font-effect-crackle",name:"crackle"}
]
};
$scope.mddl2 = $scope.ddl2option.data[0];
$scope.opfun = function(selectedModelValue){
//alert(selectedModelValue); // Here I can get the value only
}
}
<强>的index.html 强>
<select
id="dflfnt"
ng-change="opfun(mddl1)"
ng-model='mddl1'
ng-options='option.name for option in ddl1Options.data'
></select>
<select
id="3dfnt"
ng-model='mddl2'
ng-change="opfun(mddl2)"
ng-options="option.name for option in ddl2option.data"
></select>
<h5>mddl1</h5>
<pre>{{mddl1}}</pre>
<h5>mddl2</h5>
<pre>{{mddl2}}</pre>
</div>
答案 1 :(得分:0)
我通过$watch
指令为您提供了工作demo。
你的HTML没有一点点轻松:
<select
id="dflfnt"
ng-model='mddl1'
ng-options='option.name for option in ddl1Options.data'
></select>
<select
id="3dfnt"
ng-model='mddl2'
ng-options="option.name for option in ddl2option.data"
></select>
并且您的控制器可以完全控制模型是否更改:
$scope.$watch('mddl1', function(mddl1) {
console.log(mddl1);
});
如果您想观看展位,请使用:
$scope.$watch('mddl1 + mddl2', function(value) {
//but note this value is concatenated
console.log(value);
//you should access the values over the $scope.mddln now
});