javascript - 选择框上的 AngularJS orderBy 无法按预期工作。

标签 javascript html json angularjs

我正在尝试将旧的 PHP/JS 项目转换为直接的 AngularJS。

我遇到的问题是我的选择框上的 orderBy:"name" 只能工作。

例如,在 plunker(如下)中,如果您打开建筑物下拉列表,它似乎按正确的字母顺序排列。然而,有一些只是在整个下拉菜单中随机错放的。

另一个奇怪的事情是 JSON 文件已经按字母顺序排列,所以我不确定这是怎么回事。

我是 AngularJS 的新手,所以我知道我错过了一些小东西。任何帮助将不胜感激。谢谢!

骗子:http://plnkr.co/edit/wHSERdfKLaYaaSMBph73

JSON 示例:

{
    "id": 110,
    "name": "Administration Center",
    "address": null,
    "latitude": "41.256326",
    "longitude": "-95.973784",
    "content": "",
    "overlay": "g|xzFnywhQ?^^??j@M??^r@??_@K??kA",
    "url": "",
    "type_id": 3,
    "show_marker": 0,
    "show_label": 1,
    "custom_marker": "",
    "created_at": "2013-07-10 15:40:09",
    "updated_at": "2013-07-10 15:42:50",
    "color": "#08c"
}

最佳答案

你的plunker在你的依赖关系的顺序上有一些错误(即: Angular 之后的jquery等。开发控制台中有一条错误消息)。使用 Angular 和 jquery 时,必须首先包含 jquery。

<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="http://code.angularjs.org/1.2.0-rc.3/angular.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="//cdn.jsdelivr.net/underscorejs/1.5.1/underscore-min.js"></script>

这是您的修复后的演示:http://plnkr.co/edit/92zvkjP1cx1wBlGqwB4D?p=preview

如果您使用 orderBy 过滤器,则无需在 Controller 中对数据进行排序。

html

<div ng-repeat="(key,menu) in menus">
    <h1>{{typeIds[key]}}</h1>
    <select ng-model="selectedlocation" 
            ng-options="item.id as item.name for item in menu | orderBy:'name'">
    </select>
</div>

js

function menuController($scope, $http) {
    // probably not the best way to do this
    $scope.typeIds = {3: "Buildings", 6: "Parking (Fac/Staff)", 7: "Parking (Public)", 8: "Parking (Student)", 11: "Landmarks"};

    $http.get('locations.json').then(function(res) {
        $scope.locations = res.data;
        $scope.menus = _($scope.locations).groupBy('type_id');

        /*
        // This is not needed anymore
        //Convert to array so it sorts correctly on the view side. 
        $scope.orderedMenus = [];
        _($scope.menus).each(function(data, key) {
            $scope.orderedMenus.push({"key" : key, "data" : data})
        });
        */
    });
}

关于javascript - 选择框上的 AngularJS orderBy 无法按预期工作。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19390669/

相关文章:

javascript - d3pie错误: no data supplied on d3pie. js

html - 如何让div一直垂直向下缩放?

html - 页脚后有很多空白

java - 使用流式 api 提取部分 json 字符串并转换为 jsonTree (Jackson)

ios - NBA 数据 JSON 解析 Swift

javascript - 当窗口较小时窗口会调整大小,即使窗口宽度较大后也保持不变

javascript - .innerHTML 应用于两个 div,而应仅应用于一个

javascript - 在 lodash 中 reduce 后继续链

javascript - AngularJS $location.search

ios - 可能从 JSON 数据对象解码的 Codable 结构数组