gpt4 book ai didi

javascript - 如何在下拉列表中为选项添加附加值,以及如何在 angular js 1.x 中选择选项时获取该值

转载 作者:行者123 更新时间:2023-11-29 23:22:17 25 4
gpt4 key购买 nike

我在 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');

最佳答案

当您使用angularjs 时,您不需要使用jQuery

要在下拉列表中获取所选值,您需要使用 ng-modelselect 建模然后该值将即时存在。这就是 angularjs 的美妙之处。

此外,如果您有兴趣动态添加选项,最好使用 ng-repeat要做到这一点。并在需要添加另一个选项时插入数组。该选项将添加到 selectangularjs

的又一 block 美

这里

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


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

关于javascript - 如何在下拉列表中为选项添加附加值,以及如何在 angular js 1.x 中选择选项时获取该值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50249974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com