我在jQuery中有以下代码。我想知道Angular Js 1.x版本中上面的等效代码是什么?
<select id="select">
<option value="1" data-foo="dogs">this</option>
<option value="2" data-foo="cats">that</option>
<option value="3" data-foo="gerbils">other</option>
</select>
// JavaScript using jQuery
$(function() {
$('select').change(function() {
var selected = $(this).find('option:selected');
var extra = selected.data('foo');
});
});
var sel = document.getElementById('select');
var selected = sel.options[sel.selectedIndex];
var extra = selected.getAttribute('data-foo');
答案 0 :(得分:1)
使用jQuery
时,您不需要使用angularjs
。
要在下拉列表中获取所选值,您需要使用ng-model
对select
进行建模,然后该值将在那里动态显示。那是angularjs
的美丽。
此外,如果您有兴趣在飞行中添加选项,请更好地使用ng-repeat
来执行此操作。当您需要添加其他选项时,请按下阵列。该选项将添加到select
。另一件美女angularjs
下面
angular.module('app',[]).controller('ctrl', function($scope){
$scope.options = [{value : 1, attr: "dogs" },{value : 2, attr: "cats" },{value : 3, attr: "gerbils" }];
$scope.data = $scope.options[0]
$scope.select = 1;
$scope.add = function(){
$scope.options.push({value : $scope.options.length + 1, attr: 'option'})
};
$scope.getFoo = function(){
$scope.data = $scope.options.find(o=> o.value == $scope.select)
}
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='ctrl'>
<select id="select" ng-model="select" ng-change="getFoo()">
<option ng-repeat="option in options" value="{{option.value}}" data-foo="{{option.attr}}">{{option.attr}}</option>
</select>
<button ng-click="add()">Add option</button>
{{data.value}}
{{data.attr}}
</div>
&#13;
答案 1 :(得分:0)
将值添加到作为ng-repeat的数据源提供的模型中,并为下拉列表设置ng-model。并使用ng-model获取下拉值。