Showing posts with label Angular.js. Show all posts
Showing posts with label Angular.js. Show all posts

Sunday, August 25, 2013

Minimizing Angular.js in .NET MVC4 the right way

Introduction

When we write angular application we cannot minimize javascript file as we do regularly. This is because in angular most of the injectables are declared as strings bus used as properties. If we would minimize the js files the properties would be changes into letters (a, b,etc...) and angular won't be able to find these injectables declarations. 

In MVC4 we can use bundles to minimize js and css files. Unfortunately to my experience these classes are not working well with O.O javascript. I have also encountered other problems with naming conventions in files. If error is thrown while minimizing js file, the file will be served, but, will include stack trace of the error appended into the beginning of the javascript file, and this is not good to say the least. 

YUI Compressor

Yahoo has a pretty good compressor engine that allows to do the same and even more. Luckily, in MVC4 we can import YUI dlls to our project and override default compression engine of MVC bundles to use YUI instead. It can the be configured to leave angular injectables as-is while compressing and concatenating all the rest. 

Importing YUI 

First of all be sure you use 4.5 framework as YUI dlls requires that. Open "Package Manager Console" and enter the following line:

install-package YUICompressor.NET.Web.Optimization


This will install all the prerequisites and the YUI dlls.

Switching to YUI

Now we should override the default behavior of the bundles and direct MVC to use YUI minimization engine instead.
Inside BundleConfig.cs file we should create javascript compressor configuration instance and set ObfuscateJavascript = true. This configuration will direct YUI engine to leave the variables naming as is.

            var jsCompressorConfig = new JavaScriptCompressorConfig
            {
                ObfuscateJavascript = true
            };
            var jsTransform = new YuiCompressorTransform(jsCompressorConfig);

We now can start switching our bundles to work with YUI.
Assuming we keep naming conventions in our project file system we can bundle our js files as follows:

            bundles.Add(new Bundle("~/js/controllers.js", jsTransform).Include(
                        "~/js/controllers/controllers.js",
                        "~/js/controllers/*-controller.js"));

            bundles.Add(new Bundle("~/js/filters.js", jsTransform).Include(
                        "~/js/filters/filters.js",
                        "~/js/filters/*-filter.js"));
Taking into account that all of our controllers end with -controller.js we now have bundle that will include all the controllers in the controllers directory without the need to add anything after creating the new controller.

Sunday, August 18, 2013

Angular.js example from usergroup

Introduction

At 19/08/13 I've spoke at Gil Fink  UserGroup at Sela about introduction to Angular.js. Below a short overview of the example app presented.

Structure

When building Angular application is is most important to divide it into modules. The current example was relatively small so the modules division was made by different components of the framework (e.g. controller, services, filters, etc..). 
Note, that if the application is large and complex the division to modules should be made by features rather than by components. Each module should then contain everything related to the feature. It will allow us to take the feature to another Angular project with ease.

Please note, there are 5 examples in the main directory from the most basic to the most complex, I'll overview the last as it includes all the other examples as well

Bootstrapping

As an entry point I have the application.js file which defines all the modules available for the projects including the dependencies between them.

window.directives = angular.module('directives', [], function () {
});
window.services = angular.module('services', [], function () {
});
window.filters = angular.module('filters', [], function () {
});

Right after that, the main module configures the routes.

window.application = angular.module('myMovies', 
    ['directives', 'services', 'filters'], function ($routeProvider) {
    $routeProvider
        .when('/', {
            controller: 'mainCtrl',
            templateUrl: 'templates/movies_list_view.html'
        })
        .when('/about', {
            templateUrl: 'templates/about_view.html'
        })
        .when('/movieDetail/:id', {
            controller: 'movieDetailController',
            templateUrl: 'templates/movie_detail_view.html'
        })
        .otherwise({
            templateUrl:'templates/404.html'
        })
});

The $routeProvider has two functions. when - used to declare a valid route either with or without parameters and otherwise - will redirect at any illegal route entered.

Controllers

Two controllers are available one for displaying the movies on the main page and the other for displaying additional details about a movie
The mainController requests the mockService to get the movies data, and also defines event to remove movie on click.
The movieDetailController uses the same service to get movie by id. Note, the movie id is passed as a parameter in url (not as querystring). The controller then reads the parameter with the $routeParams provider.

Services

One service is available. the mockService gets it's data statically from another js file with timeout to simulate a delay.
Because I used timeout function there I need to call $scope.$apply() inside controller to notify Angular about changes to the data. 

        $scope.$apply(function () {
            $scope.model = {
                movie: movie
            }
        });

Normally, when fetching data from server we should use $http service to get the data, the $http service will take care for notifying about changes

Filters

Build-in filters are used in movies list template to filter movie results by the search field. Also, one custom filter is available to convert minutes to more visualisable format.

Templates

Templates for every page is available and are loaded when route gets resolved. Also 404 template is available for the 'otherwise' function.

Conclusion

To create this example I've simplified the structure of the project. The file structure should be a bit different and I hope that soon I'll post a full project example showing the structure as I see it. 
I also simplified the code for the sake of this example, so probably it won't look 100% the same in real life project.

The code examples are available here: http://goo.gl/1xlQFS

I'll be glad for every input you may have about this post or the examples. 

Sunday, May 26, 2013

Angular.js: Using promise injectable inside callback

Often when I want to make a http request from angular.js I write a service. Service can be used as injetable whenever needed.
In angular however there are promise service that implements the promise pattern. Using them can make the asynchronous work easier. For those who are unaware of what promises are there is a documentation available here.

When implementing the promise pattern inside service you probably will have to run the deffered.resolve() command inside the callback as javascript is most of the time asynchronous. The weird thing for me was that it does not work  from the callback. The function registered inside .then function will not run!

Consider the following example:
angular.module('myModule', [], function () {
})
    .service('dataService', ['$q', '$timeout', function ($q, $timeout) {
        this.getData = function () {
            var deferred = $q.defer();
            $timeout(function () {
                someHttpGetter.getData(data);
                deferred.resolve(data);
            }, 2000);
            return deferred.promise;
        };
    }]);

In this example the callback inside .then function will work correctly. On the other hand, this example:

angular.module('myModule', [], function () {
})
    .service('dataService', ['$q', '$timeout', function ($q, $timeout) {
        this.getData = function () {
            var deferred = $q.defer();
            $timeout(function () {
                someHttpGetter.getData(function (data) {
                    deferred.resolve(data);
                });
            }, 2000);
            return deferred.promise;
        };
    }]);

Here, the deffered.resolve() is inside a callback. It will not work.
The reason for that is that in the first example the resolve will happen inside the digest cycle of angular, while in the second example the resolve happens in callback, thus, outside the cycle.
The solution for this (as I found) is to inject the rootScope to the service and invoke the $rootScope.$apply() right after the resolve method. The complete working example should look like this:

angular.module('myModule', [], function () {
})
    .service('dataService', ['$rootScope', '$q', '$timeout', function ($rootScope, $q, $timeout) {
        this.getData = function () {
            var deferred = $q.defer();
            $timeout(function () {
                someHttpGetter.getData(function (data) {
                    deferred.resolve(data);
                    $rootScope.$apply();
                });
            }, 2000);
            return deferred.promise;
        };
    }]);

Wednesday, May 22, 2013

AngularJS User Group @ Microsoft Raanana

Yesterday I gave session about AngularJs at Microsoft Raanana. The sessions gave first impression about AngularJS.

You can find the presentation and the code here

Thanks for everyone who came! Hope you enjoyed.