Introduction to AngularJS Framework

Posted on Posted in Javascript, Stories, Technology Center

AngularJS Framework on Single Page Applications

The goal of many modern web application developers these days is to create an app that will give the users a desktop-app-like experience. For that thing to happen, they abstracted the multiple page reloads in a typical web application and just made it to load a single page and do everything else inside it. This type of design is called Single Page Application or Single Page Interface.

A Single Page Application (SPA) is an app that only requires a browser to load just a single page. The browser wont have the burden to reload the page anymore on every minimal interactions that the user makes and instead, focus only on the things that required changes.

AngularJS by Google

Once again, Google has somehow prepared for this trend, and developed a framework called AngularJS. This framework makes our work as front end developers much easier. It is fully packed with features such as data-binding, templating, form validations and many more. In this blog, we’re gonna try to create an angular application.

Getting Started

Before anything else, we need to include the source of AngularJS to our main page.

Directives

Directives are attribute-like code in the html page that is only understandable by AngularJS. The first directive that we need to know is ngApp. This directive tells the AngularJS compiler that the page is an angular module/application.

We must put ngApp to the parent tag. The best practice is to put the said directive in the root tag of the document which is. It is much readable and can be noticed easily if it’s placed there.

Controllers

Controllers are functions used to initialize the model objects, and other utility functions that’ll be used inside the tag where the directive ng-controller is defined. In our example, we’ll use MainController as the name of our controller.

The code of our page will now look like this

The value of the ngController directive should also be the name of the function it is pointing to. Controllers (functions) have special parameters with fixed names like $scope. $scope is an object where model variable/objects and functions are placed so that it can be accessible inside the tag bound with ngController. In the example above, we put the model named myName and assigned the string literal “Jimmy”.

Two Way Data-Binding

Now what I want is to show the value of the model myName in the browser, we can achieve it by putting the variable name enclosed with double curly braces inside an html DOM Element

Hi {{myName}}!

Now try to view your code in your browser. If you coded it right, you’ll see the words “Hi Jimmy!”

Now we’re gonna add another directive in our vocabulary. The directive ngClick acts like the onclick attribute in html. The difference is that the variables and functions used in the value of ngClick should be initialized in the $scope variable inside its corresponding controller. It can also directly access special variables like $scope and $location. Let’s add a button that will change the value of $scope.myName.

MainController will now be

function MainController($scope){
    $scope.myName = "Jimmy";
    $scope.changeName = function(){
        $scope.myName = "John";
    }
}

and our page will be

AngularJS offers a real-time update wherein updating the model will change the view and vice versa.

If we try to run this code in the browser and click the button, the name in the greeting message will be “John” because the value of myName is changed to “John.”

Try adding an input tag inside the body tag and put a directive called ng-model and assign “myName” as its value then run the code. The directive ngModel is for tags such as input, select, and textarea tags.

If we try to change the value in the input tag, the name in the greeting will change too then the value of $scope.myName will be the value of the input tag too.

Templating

Observe this code:

If we run this page, it’ll look like this:

Loading Different Views: Single Page Approach

AngularJS also gives the ability to show different views in the page depending in the URL that the user visited. The directive ngView and some minimal configurations allow us to do this.

First, we must bind ngView with a tag in the body of our document. Anything inside the tag bound with ngView will be erased upon startup

Then we assign a value in the ngApp directive that we declared in the html tag. The value of ngApp will be the application/module name of the page.

Then we declare and get the instance of the angular module with the following code:

var app = angular.module("myApp", []);

Then we configure the routing by putting:

app.config(function($routeProvider){
	$routeProvider
		.when("/", {controller: MainController, templateUrl: "pages/home.html"})
		.when("/edit", {controller: EditController, templateUrl: "pages/edit.html"})
		.otherwise({redirectTo:'/'});
});

The $routeProvider is a special parameter that is used for routing. Its when function is for describing the URL that’ll appear in the browser’s address bar, what controller the view will use, and the URL to where to get the template.

There are three html pages that we used in the example: the main page, home.html, and edit.html. Here’s what home.html and edit.html look like:

pages/home.html – The html template that the base URL will load.

Hello {{myName}}!

pages/edit.html – The html mapped to /edit url.

These pages are retrieved using Ajax queries and its contents are appended inside the tag bound with ngView directive.

Sharing Data Between Two Controllers

In our example, we used two controllers. There’s still one little problem with this. It’s that different controllers have different scopes. That means we can’t access the data of anything declared in the $scope of a controller within a different controller. To be able to do this, we must declare a shared attribute or data that every other controllers can access and change.

We can do this by creating a service:

app.service("$globalVars", function(){
	var myName = "Jimmy";
	return {
		getMyName : function(){
			return myName;
		},
		setMyName : function(value){
			myName = value;
		}
	}
});

$globalVars is the name that I decided to label it. We can change the name of the service to anything we want except the angularjs’ reserved words but the name should be consistent in all controllers. We can access it on every controllers just by adding it to the parameter of these controllers. Sure there are different purposes for a service, but we’ll stick to just creating a global variable.

The two controllers now will be:

function MainController($scope, $location, $globalVars){
	$scope.myName = $globalVars.getMyName();
	$scope.editName = function(){
    	    $location.path("/edit");
        }
}

function EditController($scope, $location, $globalVars){
	$scope.myName = $globalVars.getMyName();
	$scope.goBack = function(){
		$globalVars.setMyName($scope.myName);
		$location.path("/");
	}
}

$location is another special parameter in controllers that controls the path of the app. $location.path(“/edit”) just tells the app to go to the URL /edit and load its corresponding view then access its corresponding controller. $globalVars is added to the parameter of the controllers. Its content is what the function returned in the service declaration.

With home.html and edit.html shown above, the main page of our example will be:

If we run the code, it’ll be just a simple changing of name in the greeting with the code implementing the binding and routing of different views used by the application.

Conclusion

AngularJS is one of the most awesome framework when it comes to single page applications. It can also be used with applications without the single page implementation. There are localization, AngularJS form validation, pluralization and many more feature that can be used to make the development of a programmer easier. The next things that should be studied after this is AngularJS and its back-end communication.

One thought on “Introduction to AngularJS Framework

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.