Вопрос

I just started learning Angular and would have thought this is trivial, but I can't make sense of it..

I have a list of expenses, ordered by the date property:

<div class="expense" ng-repeat="exp in expenses | orderBy:'date'">
    <div class="c date">{{ exp.date | date: 'dd/MM/yyyy' }}</div>
    <div class="c amount">{{ exp.amount | currency:'£' }}</div>
    <div class="c category">{{ exp.category }}</div>
    <div class="c note">{{ exp.note }}</div>
</div>

I am initialising some expenses in the controller:

$scope.expenses = ({date: '01/05/2013', amount: 137, category: 'Groceries', note: ""},
      {date: '01/03/2011', amount: 100, category: 'Groceries', note: ""},
      {date: '05/05/2013', amount: 10, category: 'Entertainment', note: ""});

These are all displayed in the correct order at first (2011, 2013, 2013). I can then successfully add an expense to this list:

 $scope.add_exp = function() {
    $scope.expenses
    .push({date: $scope.date, amount: $scope.amount, category: $scope.category, note: $scope.note});

    // Reset fields
    $scope.date = '';
    $scope.amount = '';
    $scope.category = '';
    $scope.note = '';
  };

Here's the catch -- the newly added expenses are in fact ordered, but the ones present at initialisation are not taken into account.

For example, I add an item with the year 2014 into my expenses. The new order will be 2011, 2013, 2013, 2014. I then add an item with the year 2007, expecting it to be the first in the list. Instead, the new order is 2011, 2013, 2013, 2007, 2014 (it gets injected after the original expenses).

I've tried manually filtering expenses at the end of the add_expense function, which didn't make a difference, and using $scope.$apply(), which gives me an error ($apply already in progress).

Это было полезно?

Решение

Instead of adding date like date:'01/05/2013' use date: new Date('01/05/2013') and it will work perfectly

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top