angular实现select的ng-options

时间:2021-09-14 17:10:13

html

<div ng-controller="ngSelect">
<select ng-model="vm.selectVal" ng-options="o.title for o in vm.optionsData">
<option value="">请选择</option>
</select>
</div>

js

angular实现select的ng-options
var app = angular.module("app",[]);
app.controller("ngSelect",function($scope){ var vm = $scope.vm = {}; //数组对象用来给ng-options遍历
vm.optionsData = [{
title : "angularJs"
},{
title : "emberJs"
},{
title : "backboneJs"
},{
title : "knockoutJs"
}]; })
angular实现select的ng-options

给ng-options自定义option的value值

<select ng-model="vm.selectVal" ng-options="o.id as o.title for o in vm.optionsData" ng-change="selectChange()">
<option value="">请选择</option>
</select>

添加了id属性作为option的value
你可能会在页面视图看到option生成的value为0,1,2,3,是因为angular会自动添加索引为value的值
让我们来个ng-change事件监控来看看

angular实现select的ng-options
vm.optionsData = [{
id : 4543,
title : "angularJs"
},{
id : 546,
title : "emberJs"
},{
id : 456,
title : "backboneJs"
},{
id : 75,
title : "knockoutJs"
}]; $scope.selectChange = function(){
//添加了ng-change事件来试试id值的输出
console.log(vm.selectVal);
}

相关文章