javascript - 在 Javascript 和 AngularJS 中查找数组中的值

标签 javascript html angularjs

这是我的代码。当组合框的值更改时,我需要找到一种方法来搜索 $scope.options 中数组中的值。

<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html ng-app>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="../angular.js"></script>
        <script>
            function reportController($scope){
                $scope.options=[{name:'option 1', id:'1'},{name:'option 2', id:'2'},{name:'option 3', id:'3'}];

                $scope.selectedValue = {name:'option 1', id:'1'};
                $scope.updatedName = $scope.selectedValue.name;
                $scope.updatedId = $scope.selectedValue.id;

                $scope.updateCombo = function()
                {
                    console.log("inside updateCombo");

                    comboVal = document.getElementById("nameCombo").value;
                    arrIndex = $scope.options.indexOf(comboVal);
                    console.log("combo box selected value = " + comboVal + " :: index = "+ arrIndex);
                    //$scope.selectedValue=$scope.options[index];
                }
            }
        </script>
    </head>
    <body>
        <div ng-controller="reportController">
            <select id ="nameCombo" ng-model="selectedValue" ng-change="updateCombo()">
            <option ng-repeat="value in options" >{{value.name}}</option>
            </select>
            <p>Name : {{selectedValue.name}}</p>
            <p>ID : {{selectedValue.id}}</p>
        </div>
    </body>
</html>

我尝试从函数调用中传递索引,但这确实有效。我也尝试过 indexOf,但这不起作用,因为我只有名称,没有组合框中的 id。

最佳答案

你可能想做这样的事情:

<select ng-model="selectedValue" ng-options="opt.name for opt in options"></select>

所选值是“ng-model”并会自动更新。

检查这个Fiddle我为您制作的示例。

关于javascript - 在 Javascript 和 AngularJS 中查找数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23624334/

相关文章:

javascript - 我怎样才能对 AngularJs 中的 hashchange 事件采取行动

Java REST 服务应答需要太多时间

javascript - 使用单选按钮的 checkedValue 绑定(bind)

javascript - 无法使用 Lighttpd 访问 Raspberry Pi 上的 socket.io.js [Node.JS & Socket.IO]

javascript - 单击搜索栏转到链接

jquery - 如何选择在mvc中动态选择的css类

html - 显示 : table-cell issue in Firefox

python - 如何用漂亮的汤解析长网页?

javascript - 为每个 div 添加类链接

javascript - 我将范围值传递给我的指令,但它是未定义的