2014-12-13 116 views
3

UPDATE:NG重複排序依據對象

我的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/

+0

按照什麼順序你試圖把他們嗎?他們已經準備好了。 – JLRishe 2014-12-13 01:43:31

回答

11

您可以將過濾器並不適用於普通的對象,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

+0

我看到它的工作,但我的'NG-include'不能正常工作,甚至我想是這樣的'' – 2014-12-14 01:59:48

+0

@AbuHamzah您可以更新您的問題,以顯示新的代碼你試過了嗎? – JLRishe 2014-12-14 14:41:18

+0

我已經取代我的代碼與我有什麼張貼一個答案,但感謝您的幫助1+ – 2014-12-15 16:31:33

-3

幸得ryeballar

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

代替使用鍵 - 值對象,爲什麼不使用陣列的? ng-repeat通過迭代對象/數組的索引來排序迭代。

FORKED DEMO

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

您更改了自己的要求並回答了它。它可能已經解決了你目前的問題,但並沒有回答這個問題。 – Sandy 2015-10-07 21:36:20

1

,所以我認爲這會工作,它也保持了相同的對象指針,

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; 

    } 
}])