按控制器设置默认顺序

时间:2016-02-15 10:57:52

标签: javascript angularjs controller

有人可以帮我解决这个问题吗 - 可能是非常的菜鸟问题,好吗?

我有以下HTML代码:

<!doctype html>
<html>
<head>
    <title>Starting Angular</title>
</head>
<!-- The ng-app directive triggers load and setup of AngularJS
     after the DOM is loaded.
     It sets the tag as the root of the AngularJS app.  -->
<body ng-app="cardApp">
    <!-- Identify the controller and model to be used. -->
    <div ng-controller="MainController">
        <!-- The ng-bind gets data from the model. -->
        <h1 ng-bind="greeting"></h1>
        <br />
        Sort by:
        <select ng-model="orderProp">
            <option value="suit">Suit</option>
            <option value="numOrd">Number</option>
        </select>

        <table>
            <tr><th>Number</th><th>Suit</th></tr>
            <!-- Populate the HTML with each object in the cards model. -->
            <tr ng-repeat="card in cards | orderBy:orderProp ">
                <td ng-bind ="card.number"></td>
                <td ng-bind ="card.suit"></td>
            </tr>
        </table>
        <br />
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
    <script src="js/controllers.js"></script>
</body>
</html>

我想设置数字显示的卡的默认顺序。如何修改此控制器呢?

// Register controller with angular module.
var cardApp = angular.module('cardApp', []);

// The controller is a constructor function that takes a $scope parameter.
// The controller lets us establish data binding between the controller and the view.
// The model is initialized with the $scope parameter.
cardApp.controller('MainController', ['$scope', function ($scope) {$scope.val = "numOrd"
// Scope ensures that any changes to the 
// model are reflected in the controller.
// Here we create an initialize a 'title' model.
$scope.greeting = "AngularJS Hello World!";

// Define cards model which stores an array of objects.
$scope.cards = [
    { "number": "2", "suit": "Hearts", "numOrd": 2 },
    { "number": "10", "suit": "Spades", "numOrd": 10 },
    { "number": "5", "suit": "Spades", "numOrd": 5 },
    { "number": "Q", "suit": "Hearts", "numOrd": 12 }
    ];
}]);

提前致谢!

3 个答案:

答案 0 :(得分:0)

您可以在Array类中使用函数'sort'。它会对您的卡阵列进行排序。

array.sort([compareFunction])

在这种情况下:

$scope.cards.sort(function(a, b){
  return a['numOrd'] - b['numOrd'];
});

有关'sort'的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

答案 1 :(得分:0)

另一种方法是使用另一个属性suitOrd扩展您的模型,该属性为您的每个套装指定一个特定的数字。多亏了这个你可以按这个属性排序,因为它将是一个数字

答案 2 :(得分:0)

您要做的是将其添加到您的js。

$scope.orderProp = "numOrd";