如何通过 #ID 100% AngularJS获取元素SELECT中的文本和值

How to get Text and Value in element SELECT by #ID 100% AngularJS

本文关键字:文本 SELECT 元素 #ID 何通过 100% AngularJS 获取      更新时间:2023-09-26

有一种更好的方法来做AngularJS,用更少的代码行,我的例子..?这个想法是用AngularJS和jqLite使它100%。

链接示例 我的代码解决方案:http://jsfiddle.net/EOM/xecymL9t/

.HTML:

<div data-ng-controller="Main" data-ng-app>
  <select id="yo" data-ng-model="selection" data-ng-change="sample(selection)" required="required">
    <option value="11" selected="selected">Name 2</option>
    <option value="10">Name 1</option>
    <option value="">SELECT DEFAULT ANGULAR INIT</option>
    <option value="12">Name 3</option>
  </select>

在控制台中查看到浏览器的显示 (F12)

AngularJS:

function Main($scope, $document) {
$scope.sample = function(myvalue) {
        // Get By ID
        var e = $document[0].getElementById('yo');
    // Get all options select
    e = angular.element(e).find('option');
    // Loop
    angular.forEach(e, function(v, k){
        // Is option selected..?
        if(angular.element(v).prop('selected')){
        // Get Text option selected
        console.log('Text: '+angular.element(v).text()); // Text
      }
    });
    console.log('Value: '+myvalue) // Value
}}

这有点短,但我不知道你是否认为它是 100% AngularJS + jqLite。AngularJS文档说你应该使用标准的DOM API进行高级查询(jqLite的find仅限于按标签名称查找)

function Main($scope, $document) {
  $scope.sample = function(myvalue) {
    var e = $document[0].getElementById('yo')
      .querySelector('[value="' + myvalue + '"]');
    // Get Text option selected
    console.log('Text: '+angular.element(e).text()); // Text
    console.log('Value: '+myvalue) // Value
  }
}

您可以在此处检查解决方案

基于解决方案"jbMartinez",我看到了一个更简单的解决方案缩短了手柄。并检索所选选项的文本。

关于兼容性"Niclas Larsson"是>= IE9或更高版本,因为我使用的是AngularJS 1.5.0并且它不支持<= IE8

正在说,将其视为最终解决方案,或者可能是更好的方法..?

代码示例仅在 JS 中更改:

function Main($scope, $document) {
$scope.sample = function(myvalue) {
    var myval = (myvalue)?myvalue:'';
    // Get text select
    var mytext = $document[0].querySelector('#yo [value="' + myval + '"]').text;
    // Show Text option selected in console
    console.log('Text: '+mytext); // Text
    console.log('Value: '+myval) // Value
} }

链接示例运行在这里