【问题标题】:ng-repeat orderBy objectng-repeat orderBy 对象
【发布时间】:2015-02-11 19:32:44
【问题描述】:

更新:

在我的 html 页面上,我使用如下:

<section ng-repeat="template in templates">
        <ng-include src="template"></ng-include>
    </section>

但问题是我需要特定顺序的特定文件,所以有没有办法可以控制顺序呈现的方式?

我正在尝试订购一个对象,我该怎么做,我已经在网上搜索过,然后才在这里发布。

function MyCtrl($scope) {
    $scope.templates = {
        template_address: "../template/address.html",
        template_book: "../template/book.html",
        template_create: "../template/create.html" 
    };



<div ng-app ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="(name, path) in templates">{{name}}: {{path}}</li>
    </ul>
</div>

http://jsfiddle.net/abuhamzah/6fbpdm9m/

【问题讨论】:

  • 你想按什么顺序排列它们?他们已经准备好了。

标签: angularjs angularjs-ng-repeat ng-repeat


【解决方案1】:

您不能将过滤器应用于普通对象only to arrays

您可以做的是在控制器中定义一个方法来将对象转换为数组:

$scope.templatesAry = function () {
    var ary = [];
    angular.forEach($scope.templates, function (val, key) {
        ary.push({key: key, val: val});
    });
    return ary;
};

然后过滤:

<li ng-repeat="prop in templatesAry() | orderBy:'-key'">
     {{prop.key}}: {{prop.val}}
</li>

Example

【讨论】:

  • 我看到它可以工作,但我的ng-include 无法正常工作,即使我尝试了类似&lt;ng-include src="ary.val"&gt;&lt;/ng-include&gt; 的操作
  • @AbuHamzah 您能否更新您的问题以显示您尝试过的新代码?
  • 我已将我的代码替换为我发布的答案,但感谢您的帮助 1+
  • 得到控制台错误:10 $digest() iterations reached. Aborting!
  • 您应该将函数的结果缓存在某处以避免@MikeCarson 得到的无限摘要错误。
【解决方案2】:

功劳归于黑麦

https://stackoverflow.com/a/27466368/275390

为什么不使用数组,而不是使用键值对象? ng-repeat 按被迭代对象/数组的索引对迭代进行排序。

FORKED DEMO

  $scope.templates = [
    'create.html',
    'book.html',
    'address.html'
  ];

【讨论】:

  • 您更改了自己的要求并回答了它。它可能已经解决了您当前的问题,但没有回答问题。
【解决方案3】:

所以我认为这会起作用,并且它还保持相同的对象指针,

app.filter('orderObjectBy', [function()  {
  return (filterObj, prop) => {

let arr = []
//below is the loadash function you can use for in also
_.forEach(filterObj, function(value, key)  {
  arr.push({
    key: key,
    value: value
  });
});

let sortedArr = _.sortBy(arr, val => val.value[prop]);

for (let variableKey in filterObj) {
  if (filterObj.hasOwnProperty(variableKey)) {
    delete filterObj[variableKey];
  }
}

for (let data of sortedArr) {
  filterObj[data.key] = data.value;
}


    return filterObj;

  }
}])

【讨论】:

    【解决方案4】:

    你不需要把它保存为 Object ,将 Key 包含在 data 字段中,并使其成为数组,之后你可以将它用作 item.key ;你可以用 _.omit 删除它

    过滤器 = 功能(项目){

    过滤={};

    _.mapObject(items,function(V,K){

    V.key = K; // Include the key in the data; your can _.omit it after 
    

    if(V.name = 'test'){filtered[K]=V;};

    });

    return _.sortBy(filtered,'anyFieldSortCoudBeThe KEY it self'); //sortBy 将返回排序后的数组 };

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      相关资源
      最近更新 更多