如何使用AngularJs或Javascript对数组进行排序?

时间:2016-04-12 17:21:33

标签: javascript arrays angularjs sorting

我想在用户选择后按字母顺序排序和显示数组,或者当我们从后端渲染数据时,我想按字母顺序显示fullName$scope.selecedControlOwnerng-click事件处理程序,一旦用户从模态窗口中选择所有者并单击确定ng-click事件触发器并在父窗口上显示值现在,我想触发排序。

$scope.controlOwnerObj.workerName是将值绑定到父窗口的ng-model。

有没有使用AngularJs或原生Javascript的解决方案?

ctrl.js

$scope.selectedControlOwner = function() {
      $scope.controlOwnerObj.workerName= $scope.selectedOwners.map(function (owner) { return owner.fullName; }).join(';');
     };


    $scope.selectedOwners = [{
            "workerKey": 46958,
            "fullName": ,"Kumari, Swapna"
        }, {
            "workerKey": 746,
            "fullName": "Mike Piero",
        }, {
            "workerKey": 150918,
            "fullName": "A J, Jyothish",
        }],

3 个答案:

答案 0 :(得分:2)

使用javascript内置sort功能

$scope.selectedOwners = [{
            "workerKey": 46958,
            "fullName": ,"Kumari, Swapna"
        }, {
            "workerKey": 746,
            "fullName": "Mike Piero",
        }, {
            "workerKey": 150918,
            "fullName": "A J, Jyothish",
        }],
$scope.selectedOwners.sort(function(a, b) {
  return a.fullName.localeCompare(b.fullName);
});

答案 1 :(得分:0)

我将只使用纯javascript,因为你给了我们这个选项

将它们从低到高排序

.service("SubjectService", function ($http, $q)
{
    var deferred = $q.defer();
    $http.get('http://genext-it.net/sma/api/subjects').then(function (response)
    {

        deferred.resolve(response);
    });

    this.getSubjects = function ()
    {
        return deferred.promise;
    }
})


.controller('theSubjectsCtrl', function($scope,SubjectService) {
    $scope.subjects = [];
var promise = SubjectService.getSubjects();
    promise.then(function (data)
    {
        $scope.subjects = data;
    });
})


<ion-view title="The Subjects" id="page1">
    <ion-content padding="true" class="has-header">
        <ion-list>

           <ion-item ng-repeat="subject in subjects" >{{subject.data}}</ion-item>
        </ion-list>
    </ion-content>
</ion-view>

它不会返回一个新数组。

结果:[3,12,12,44,121,213]

将它们从高处分类为低

  var arr = [12, 213, 3, 121, 44, 12];
    arr.sort(function (x, y) {
        return x > y;
    })

结果[213,121,44,12,12,3]

答案 2 :(得分:0)

嗨,你可以使用angularjs orderby ..

https://docs.angularjs.org/api/ng/filter/orderBy