Wednesday, October 9, 2013

AngularJS with underpants

What I really meant was AngularJS with underscore but what the heck.

AngularJS as powerful as it is doesn't really have a lot utility methods and this is where underscore comes in. Underscore provides 80-odd functions that support both the usual functional suspects: map, select, invoke — as well as more specialized helpers.

To get the most of underscore with AngularJS, you have to "provide" underscore into AngularJS via a factory method:
var myapp= angular.module('underscore', []);
 myapp.factory('_', function() {
  return window._; // underscore has been loaded before this script
 }); 
With that, we can now inject underscore into our controllers:
myapp.controller("SomeCtrl",[$scope, _, function($scope, _){
    $scope.maxVal = _.max([1,2,3]); // Returns 3
});

Which leads to a couple of pretty handy stuff like checking for undefined values:
myapp.controller("SomeCtrl",[$scope, _, function($scope, _){
    if(_.isUndefined($scope.someValue){
          // do something because someValue is undefined
    }
});
Or do a search over some array using some attribute without resorting to a loop.
myapp.controller("SomeCtrl",[$scope, _, function($scope, _){
    
var data = [{model:"T", manufacturer: "Nokia"},
            {model:"S", manufacturer:"Samsung"},
            {model:"r8", manufacturer:"Cherry Mobile"},
            {model:"One", manufacturer:"HTC"}];
//Code to fetch a Cherry Mobile phone
var phone = _.where(data, {manufacturer: "Cherry Mobile"});
// phone should be [{model:"r8", manufacturer:"Cherry Mobile"}]
});
By combining these awesome frameworks, you're setting up yourself to dish out some serious can of whoop ass.