Your code generally looks fine to me, the only thing I see that might cause issues is the line
$scope.array = $filter('orderBy')($scope.array, 'updated_at');
This line potentially generates a new array each time and assigns it to the scope. As a result the $watch
function gets fired again since the value "changed"..
What you want is a sort that does not create a new array but changes the existing array.
Here is my plunker that does what you want
http://plnkr.co/edit/TP5mzA40m77lS5gCbRfT?p=preview
angular.module('myApp').controller('MyCtrl', function($scope){
$scope.awesomeThings = ['c','b','a'];
$scope.add = function(str){
$scope.awesomeThings.push(str);
}
$scope.$watch('awesomeThings', function(){
$scope.awesomeThings.sort();
}, true);
});
As you can see I am using .sort()
function on array and I do not assign it back on the scope.
I must state that this is a bit expensive. you might want to simply write a new data structure called "sorted list" which simply does CRUD in a sorted fashion.
here is a solution I found online: https://github.com/shinout/SortedList
How to sort object by timestamp
This is how you can use .sort
in order to sort objects by timestamp
http://plnkr.co/edit/IHpK6jv8izzDMEffUz9x?p=preview
var $scope = {};
$scope.array = [{updated_at: 1438405112}, {updated_at: 1438405110}, {updated_at: 1438405102}];
$scope.array2 = [{updated_at: 1438105112}, {updated_at: 1438205110}, {updated_at: 1438405104}];
$scope.array = $scope.array.concat($scope.array2);
var ASC = 1;
var DESC = -1;
var sortOrder = ASC;
$scope.array.sort(function(a,b){
return sortOrder * ( a.updated_at - b.updated_at );
});
console.log($scope.array);
document.write('<pre>' + JSON.stringify($scope.array,{},4) + '</pre>');