2017-01-12 19 views
0

オブジェクト私は次のようになりますオブジェクトがあります。角度NG-オプション、ソート

{ 
    3019: 'Javascript', 
    3046: 'Css' 
} 

をしてから、私のようなselectでこのオブジェクトを表示する:私はアイテムをソートする必要がある

<select 
    ng-model="langChoosed" 
    ng-options="key as value for (key, value) in progLanguages" 
></select> 

選択肢の中でorderByフィルタが配列でしか動作しないようですが、どのようにオブジェクトで動作させることができますか?

+1

オブジェクトキーは**順序付けられていません* - そうではありません。 – tymeJV

答えて

1

NO順序は、別の方法としては、配列にオブジェクトを変換するために、コントローラにメソッドを定義することができ

DEMO

var app = angular.module('todoApp', []); 
 

 
app.controller("dobController", ["$scope", 
 
    function($scope) { 
 
    $scope.progLanguages = { 
 
     3019: 'Javascript', 
 
     3046: 'Css' 
 
    }; 
 
    $scope.templatesAry = function() { 
 
     var ary = []; 
 
     angular.forEach($scope.progLanguages, function(val, key) { 
 
     ary.push({ 
 
      id: key, 
 
      lang: val 
 
     }); 
 
     }); 
 
     return ary; 
 
    }; 
 
    } 
 

 
]);
<!DOCTYPE html> 
 
<html ng-app="todoApp"> 
 

 
<head> 
 
    <title>To Do List</title> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script> 
 

 
</head> 
 

 

 
<body ng-controller="dobController"> 
 
    <select class="form-control" id="selection" ng-model="currentSelected" ng-options="selection.id as selection.lang for selection in templatesAry() | orderBy:'lang'"></select> 
 
</body> 
 

 
</html>

1

オブジェクトキーには順序がないため、ソートすることはできません。

var sortedArrayFromObject = Object.keys($scope.progLanguages).map(function(key) { 
    var obj = {}; 
    obj["key"] = key; 
    obj["value"] = $scope.propLanguages[key]; 

    return obj; 
}); 

//Sort it 
sortedArrayFromObject.sort(function(a, b) { 
    return +a.key - +b.key; //since all keys are strings - do an int cast with "+" 
}); 

//Assign it 
$scope.sortedArray = sortedArrayFromObject; 

は、それを使用します:

<select 
ng-model="langChoosed" 
ng-options="item.key as item.value for item in sortedArray"></select> 
+0

は、マップを使用して別の配列を作成する必要はありません。答えをありがとう、私はマップ – Pablo

-1

はあなたのために、このOKのようなものですか、あなたのオブジェクトは、並べ替え、それは、それを使用して、配列に変換しますか

var myObj = { 
     3046:'Css', 
    3019:'Javascript' 
    }; 
    var keys = []; 

angular.forEach(myObj, function(value,key){ 
    keys.push(key); 
}); 

keys.sort(); 

$scope.myObj2={}; 
angular.forEach(keys, function(key){ 
    $scope.myObj2[key]=myObj[key]; 
}); 

、プレーンオブジェクトに適用することができないことにより、あなたのHTML

<select 
    ng-model="langChoosed" 
    ng-options="key as value for (key, value) in myObj2" 
></select> 
+0

のobj2の代わりにforEachを使用します。それはソートされません – Pablo

+1

はい、あなたは正しいです。 myObj2は、構造体 '$ scope.myObj2 = [];をプッシュする必要がある配列でなければなりません。 angular.forEach(keys、function(key){ $ scope.myObj2.push( 'id':key、 'value':myObj [key]); }); ' – Francesca