AngularJS: Sometime OrderBy does not work in ng-repeat

You must noticed that sometime OrderBy does not works, sometime works very nicely.

For example: if you have the data with following structure:
JavaScript

$scope.friends = [
      { name: 'John', phone: '555-1212', age: 10 },
      { name: 'Mary', phone: '555-9876', age: 19 },
      { name: 'Mike', phone: '555-4321', age: 21 },
      { name: 'Adam', phone: '555-5678', age: 35 },
      { name: 'Julie', phone: '555-8765', age: 29 }
];

Then it works if you code use the following code:
HTML

<tr ng-repeat="friend in friends | orderBy:'-age'">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.age}}</td>
    </tr>

But if your data structures changes a bit as follows:
JavaScript

$scope.peoples = [{
      'friend':{ name: 'John', phone: '555-1212', age: 10 },
      'relative':{ name: 'Mary', phone: '555-9876', age: 19 },
      'cousin':{ name: 'Mike', phone: '555-4321', age: 21 },
      'uncle':{ name: 'Adam', phone: '555-5678', age: 35 },
      'aunt':{ name: 'Julie', phone: '555-8765', age: 29 }
}];

HTML

<tr ng-repeat="people in peoples | orderBy:'-age'">
      <td>{{people.name}}</td>
      <td>{{people.phone}}</td>
      <td>{{people.age}}</td>
</tr>

Now, order by will not. This is because, previous data structure was an array and order by works fine on array. Now it is an Object. Order by does not works on Objects. So, first you have to make this objects to an array and then it will fine.

To make this object to an array we will use an filter. Following code will create an filter for throughout the module:
JavaScript

 ng.module('yourmodule').filter('toArray', function() {
  return function(obj, addKey) {
    if (!(obj instanceof Object)) {
      return obj;
    }

    if (addKey === false) {
      return Object.values(obj);
    } else {
      return Object.keys(obj).map(function(key) {
        return Object.defineProperty(obj[key], '$key', {enumerable: false, value: key});
      });
    }
  };
});

Now you just add this filter to html code:
HTML

    <tr ng-repeat="people in peoples | toArray | orderBy:'-age'">
      <td>{{people.name}}</td>
      <td>{{people.phone}}</td>
      <td>{{people.age}}</td>
    </tr>

😉 Order by will work like magic. Cheers!

View complete code in Plnkr.co

Advertisements

AngularJS: Add enter key to check/uncheck the check box

Sometimes clients want something different. We all know that if we check/uncheck the check box through keyboard then we have do it by space bar. But sometimes clients wants this through enter key in addition to the space bar specially for keyboard only user. So, this code can reduce your effort to write your own.

For AngularJS:

// Assume that your main module name is app, it can be anything you like.
var App = angular.module('app', []);

// Adding as directive.
App.directive('input', ['$interval', function($interval) {
    return {
      restrict: 'E', // It restricts that the directive will only be a HTML element (tag name), not an attribute.
      link: function(scope, elm, attr) {
        if (attr.type === 'checkbox') {
          elm.on('keypress', function(event) {
            var keyCode = (event.keyCode ? event.keyCode : event.which);
            if (keyCode === 13) {
              event.preventDefault(); // only when enter key is pressed.
              elm.trigger('click');
              scope.$apply();
            }
          });
        }
      }
    };
  }
]);

Same thing on jQuery is pretty easy:

jQuery(document).ready(function() {
  jQuery('input:checkbox').keypress(function(event) {
    var keyCode = (event.keyCode ? event.keyCode : event.which);
    if (keyCode === 13) {
      event.stopPropagation(); // only when enter key is pressed.
      this.trigger('click');
    }
  });
});

Very Basics of Angular JS

Recent years was a bright year for JavaScript developers, many JavaScript frameworks were born. With the advent of these frameworks, it can be quite a pain for developers to choose one suitable framework. Today we will talk with another JavaScript framework, which is Angular JS. This is very basic level discussion to kick start the Angular JS SPA (Single Page Application) Development.

Angular JS claims itself as super heroic JavaScript framework. Angular enhances HTML for web apps. It has functionalities to ease the process of developing web apps. HTML was first intended to build dynamic web apps that are Angular. Angular is what HTML would have been if it were designed to build web apps.

Before dig deeper to Angular features, we want to let you know that Angular is brought to you by Google. At least this fact can give you assurance Angular comes from the right people you can trust.

A strong understanding of basic JavaScript will be required to use Angular. If you feel that you’re beginner, keep going, Angular is not necessarily for advanced developers, but you will be dealing with a lot of objects so you have to be familiar with object oriented paradigm in JavaScript.

Digging into Angular JS:

– Angular JS is such a powerful SPA framework which allows writing client side application without JS coding or JS knowledge.

  • Here is an example how a simple app can be built without having any JS code.

– Angular JS is a full featured SPA Framework. It has all that needs for a good SPA[Single Page Application].

– So, the Big Picture of the Angular JS is like follows:

– Now, digging more deeper-

  • Directives and Data Binding: Directives refers to a feature to extends the vocabulary of HTML, it also can be seen as a way to teach your browser new tricks . With directive feature, we can create new HTML vocabulary that the browser will understand what it means and what it should do. You will find here all directives: http://docs.angularjs.org/api/ng#directive

  • View & Controller: between view controller there is a term $scope. Scope is a glue between view and controller. We also can call it Dependency Injector.

– Controller doesn’t know about the view. So, when a view calls a controller, it injects the scope automatically.

– View can be a full body DOM or a particular div. Different div can be used as different view in same html. Here the scope is the div in which the controller has declared.

  • Module:

– In Big Picture of Angular JS we saw Module is the root of everything. For a single page only one module can be added, but module can add many other module inside it by mentioning the dependencies or other module.

– Here is how module is defined with and without dependency- [We call it Dependency Injection]

  • Routers: In a configuration we can define the router. Router takes the URL after a “#” and loads related views. View can be defined in different html file.

  • Factories: factories are similar to Data-Model. There are four things in Angular JS for manage data. These are Factory, Service, Provider, Value.