Wednesday 19 February 2014

Routing in AngularJs

On this post we will see the basic of how to create Single Page Application with AngularJs.

First we need to add reference to AngularJs routing library.
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>

Then we add dependency to ngRoute module in our application module.
var myApp = angular.module('myApp', ['ngRoute']);

Next, use $routeProvider service that will be available after we include the new module to configure the routes that we have. The basic syntax is as follow:
$routeProvider.when('desired_path'), {
    templateUrl: 'location_of_the_partial_view_file',
    controller: 'controller_name_for_this_partial_view'
}
The path can contain route parameter(s) which is specified with colon (:) and could end with a star (*). Also we could have an optional parameter with a question mark (?). For more information, please see $routeProvider documentation.

Below is an example of a routes configuration:
myApp.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
    .when('/pageOne', {
        templateUrl: 'partials/page-one.html',
        controller: 'PageOneCtrl'
    })
    .when('/pageTwo', {
        templateUrl: 'partials/page-two.html',
        controller: 'PageTwoCtrl'
    })
    .otherwise({
        redirectTo: '/'
    });
} ]);

Finally we use ng-view directive to apply the configuration in our main view. For example:
<div data-ng-view></div>

Below is an example of the complete main view:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="myApp">
<head>
    <title></title>
    <script src="http://code.angularjs.org/1.2.9/angular.min.js" type="text/javascript"></script>
    <script src="http://code.angularjs.org/1.2.9/angular-route.min.js" type="text/javascript"></script>
    <script src="Scripts/app.js" type="text/javascript"></script>
    <script src="Scripts/Home/page-one-controller.js" type="text/javascript"></script>
    <script src="Scripts/Home/page-two-controller.js" type="text/javascript"></script>
</head>
<body>
    <a href="#">Home</a> | <a href="#pageOne">Page One</a> | <a href="#pageTwo">Page Two</a>
    <div data-ng-view></div>
</body>
</html>

If we want to use HTML5 url mode that is supported by recent browsers, on myApp.config(...) method add a dependency to $locationProvider service then add this line inside the method:
$locationProvider.html5Mode(true)

Tuesday 18 February 2014

Example of Using SQL Script Directly in Entity Framework

Below is a code example of how to use direct SQL script command and normal entity operation in Entity Framework 5. TransactionScope is used to cover the operations to do all if both are successful or nothing at all:

using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
                context.ExecuteStoreCommand("UPDATE Class Set Number = 20");
                context.Student.Add(new Student{ StudentId = 1, Firstname = "first", Lastname = "last" });
                context.SaveChanges();
                scope.Complete();
}

Friday 7 February 2014

Getting Started with AngularJS

On this post we will see a simple example of an AngularJS application.

First we need to reference the library on our application. We could copy the files into our project or use the Angular CDN http://code.angularjs.org/

Then create a module. Using module is not required but it is useful to have better code organisation and for reusability.
angular.module('myApp', []);
The square brackets on the second argument is for specifying any dependencies required. At the moment we don't have any.

Next create a controller:
angular.module('myApp').controller('GreetingCtrl', ['$scope', function ($scope) {
    $scope.greeting = 'Hola!';

    $scope.echoThis = function (value) {
        var processedWord = "";
        if (value) {
            processedWord = 'Echo ' + value;
        }
        return processedWord;
    };

    $scope.print = function (value) {
        $scope.result = $scope.word + value + " is printed";
    };
} ]);
Note that we use angular.module('myApp') to retrieve our module that we have created. If we have used angular.module('myApp',[]) instead, this would have recreated 'myApp' module again thus overwrited the previous module declaration. Use angular.module('myApp').controller() to define a controller inside a module.

We have also used an inline dependency injection to provide $scope service to the controller. To inject one or more components using inline annotation, we just need to put square brackets around the function, specify the components before the function and put the referred components in the same order in the function's arguments. For example:
['dep1', 'dep2', 'depN', function(dep1, renamedDep2, depN){ ... }]
Note also that the argument names can be different than the specified component names as long as they have the same order. $scope is a built-in Angular service that in simple term can be said similar to a global container object that has properties and/or functional properties (have methods attached). $scope properties will be available on the views. Line 1 shows a normal property while line 4 and 12 show functional properties.

Then we create our view:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="myApp">
<head>
    <title></title>
    <script src="http://code.angularjs.org/1.2.9/angular.min.js" type="text/javascript"></script>
    <script src="Scripts/app.js" type="text/javascript"></script>
    <script src="Scripts/Home/greeting-controller.js" type="text/javascript"></script>
</head>
<body>
    <span>{{ "Hello" + " World"}}</span>
    <div data-ng-controller="GreetingCtrl">
        {{ greeting }}
        <br /><br />
        <input data-ng-model="word" /> {{ echoThis(word) }}
        <br />
        <br />
        <button data-ng-click="print(' some text ')">Print</button>
        {{ result }}
    </div>
</body>
</html>
We have some attributes (which they called directives) in our view; ng-app is used to bootstrap AngularJs and the value is used to specify the root module to be used in the view, ng-controller to specify which controller to use for that particular section of the view, ng-model to bind input value and ng-click to execute a function when the element is clicked.

If you notice I have put the first code snippet on this post (for creating the application module) inside app.js file and the controller codes inside greeting-controller.js file.


Further reading:
Code Organization in Large AngularJS and JavaScript Applications
AngularJS Dependency Injection