Quantcast
Viewing all articles
Browse latest Browse all 10

Angular Tutorial (part 1)

I created this blog for anyone to document their progress while learning a new programming language or design software. After having used AngularJS over the last two weeks, I learned a lot and I’ve decided to do an angular tutorial. I would like to mention that all images and informations in this tutorial belong to their respective owner. This is for only for demonstration purporses.

Tutorial (Part 1)

First, the best way to get started with angularjs is to go throught their tutorial to grasp a general idea of what it is.

Your starting point will be to create your application structure.
Image may be NSFW.
Clik here to view.

In your index.html load your css, script, and bootstrap it to angularjs.

<!DOCTYPE HTML>
<html lang="en-US" ng-app>
<head>
	<meta charset="UTF-8">
	<title>Angular Application</title>
	<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
	<link rel="stylesheet" href="css/style.css">
</head>
<body>

	<div ng-view></div>
	
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
	<script type="text/javascript" src="js/angular/angular.min.js"></script>
	<script type="text/javascript" src="js/app.js"></script>
	<script type="text/javascript" src="js/controller.js"></script>
	<script type="text/javascript" src="js/directives.js"></script>
</body>
</html>

The ng-view directive allows your routing service to render a template on your master layout. For .NET programmers, it is similar to @RenderBody() which would load your partial views.
Now if you were to load your index.html in your browser, nothing would show since we haven’t set any controllers nor a route.
Let’s first take care of the routing (app.js).

"use strict";

var appTutorial = angular.module('tutorialApp', []).
						config(['$routeProvider', function($routeProvider){
							$routeProvider.
								when('/', {templateUrl: 'partials/main.html', controller: mainCtrl}).
								when('/:categoryId', {templateUrl: 'partials/category.html', controller: categoryCtrl}).
								when('/details/:itemId', {templateUrl: 'partials/details.html', controller: detailsCtrl}).
								otherwise({
									redirectTo: '/' 
								})
						}]);

For those curious about the “use strict”, it’s a feature that will throw exceptions when an action is unsafe or when your code is badly thought out.
App.js is now your main module where we configured the application with routes. The code is pretty straightforward as it tells the application which template and controller to use when we navigate to a certain page. If we happen to go navigate to an unknown link, a redirection to the homepage is done.

Note that :categoryId is a variable that the controller will use.

Important
Notice that the module was initialized with a name : tutorialApp.
We need to bootstrap the application to the main module for it to know how the routing works.
In your index.html, you need to replace

<html lang="en-US">

with

<html lang="en-US" ng-app="tutorialApp">

Try your application in your browser and you will see that it will generate an error as your controller were defined in the module but never created. Let’s create them in controller.js

function mainCtrl($scope, $http) {
	console.log("this is the mainCtrl");
}//end of function

function categoryCtrl($scope, $http, $routeParams) {
}//end of function

function detailsCtrl($scope, $http, $routeParams) {
}//end of function

$scope is used to glue data between the controller, model, and view.
$http is basically your ajax call. It will fetch the json for you.
$routeParams allows you to retrieve your route variables.

Let’s go and show something in the application.
In your partials/main.html

<ul class="nav nav-tabs nav-stacked">
	<li ng-repeat="cat in categories">
		<a ng-href="#{{cat.link}}">
			<i class="icon-chevron-right"></i> 
			{{cat.title}}
		</a>
	</li>
</ul>

<pre>
	{{categories | json}}
</pre>

ng-repeat loops through your data and repeat the li. Using the | json allows me to preview my data.
We need to fetch the data which is what mainCtrl() will do for you

function mainCtrl($scope, $http) {
	console.log("this is the mainCtrl");
	$http.get("json/categories.json").success(function(data){
		//expression categories will now have the json.
		$scope.categories = data;
		console.log('this is the data ' + data);
	});
} //end of function

If you execute your application, you will now see a list of your categories.
Upon clicking on any of them, you will see that your url is update with the categoryId variable.
As determined in your module, /:categoryId loads the category.html template and uses the categoryCtrl() controller.

function categoryCtrl($scope, $http, $routeParams) {

	$http.get('json/' + $routeParams.categoryId + '.json').success(function(data){
		$scope.serieList = data;
	});

} //end of function

As you can see the $routeParams is used to specify the variable and retrieve it.

We now have 2 pages and need to do the details page.
The details page will show information regarding the tv show Family Guy on Fox.com. It will contain information on an episode, past episodes and related shows. I decided that past episodes and related shows will be independent lists. The user will be able to toggle between table to see them.

My detailsCtrl will look like this

function detailsCtrl($scope, $http, $routeParams) {

	$http.get('json/' + $routeParams.itemId + '.json').success(function(data){
		$scope.item = data;
	});

	$scope.past = function(){
		console.log("past");
		$http.get('json/fullepisodes.json').success(function(data){
			$scope.details = data;
			$scope.predicate = '-seasonEpisode';
		});
	};

	$scope.related = function(){
		console.log("related");
		$http.get('json/family-guy-related.json').success(function(data){
			$scope.details = data;
			$scope.predicate = '-seasonEpisode';
		});
	};

} //end of function

This is a bit different than the first 2 controllers. Here I’ve assigned functions to my scope. They can be used on the view by calling them as function : past(), related().

In my view, the first step is to show the current episode.

<p>
	This is the details.html partial view
</p>


<div class="row-fluid">
	<div class="span12">
		<div class="span6">
			<img ng-src="{{theshow.thumbnail}}" alt="{{theshow.name}}">
			<h1>{{theshow.name}}</h1>
		</div>
		<div class="span6">
			<h2>{{theshow.EpisodeTitle}}</h2>
			<p>{{theshow.EpisodeDescription}}</p>
			<p>
				<strong>Playting tonight at: </strong> {{theshow.displayTime}} <br>
				on: {{theshow.channel}}
			</p>
		</div>
	</div>
</div>

<div class="row-fluid">
	<div class="span12">
		<h3>The Cast</h3>
		<ul id="cast" class="unstyled inline">
			<li>
				<img ng-src="{{theshow.husbandImg}}" alt="{{theshow.husband}}">
			</li>
			<li>
				<img ng-src="{{theshow.wifeImg}}" alt="{{theshow.wife}}">
			</li>
			<li>
				<img ng-src="{{theshow.kid1Img}}" alt="{{theshow.kid1}}">
			</li>
			<li>
				<img ng-src="{{theshow.kid2Img}}" alt="{{theshow.kid2}}">
			</li>
			<li>
				<img ng-src="{{theshow.kid3Img}}" alt="{{theshow.kid3}}">
			</li>
			<li>
				<img ng-src="{{theshow.dogImg}}" alt="{{theshow.dog}}">
			</li>
		</ul>
	</div>
</div>

TODO
Again, as i’m still learning angularjs, I’m quite sure there’s a way to display the family information more dynamically. Say this application were to show the Futurama’s cast or the American Dad’s family, this structure wouldn’t work.

Until now, this is straight forward. Let’s add the past episodes and the related show. Remember that the user must be able to toggle between them
Let’s first create the toggle function.

<div id="moreStuff">
    <div class="row-fluid">
        <div class="long50 col" ng-class="class1" ng-click="past(); predicate = '-seasonEpisode'; class1='selected'; class2='';">Past Episodes</div>
        <div class="long50 col" ng-class="class2" ng-click="related(); predicate = '-endDate'; class1=''; class2='selected'; ">Related</div>
    </div>
</div>

A lot is going on here! First let’s talk about the ng-class. Reading the first line, we can see that it’s pretty easy to understand. We initialized a class named class1. Upon clicking on the “Past Episodes” tab, class1 get the class “selected”. However, upon clicking the “Related” tab, class1 is striped of its class.
This allows me to toggle between classes.

Ng-click tells angularjs what to do on click. Therefore, when clicking “Past Episodes”, it will execute the past() function.

Now let’s show the episodes and related shows.

<table class="table table-striped" ng-init="past();">
	<thead>
		<th>Season/Episode</th>
		<th>Episode Title</th>
		<th>Description</th>
		<th>Air Date</th>
		<th>Expires</th>
	</thead>
	<tbody>
		<tr ng-repeat="info in details | orderBy: predicate"  >
			<td>{{info.seasonEpisode}}</td>
			<td>{{info.title}}</td>
			<td>{{info.description}}</td>
			<td>{{info.startDate}}</td>
			<td>{{info.endDate}}</td>
		</tr>
	</tbody>
</table>

This table has a ng-repeat which goes and display the data needed. How come does it now which to show ? Well the tabs do that for you and also because each function uses the same expression name, we don’t need to worry about syntax.

Last thing!! The tabs are working properly, but upon arrival on this page, the tabs aren’t showing anything. Well that’s because we need to initialize the table with data. This is why you see ng-init calling past() to populate the table.

Stay tuned for part2.

Download

The post Angular Tutorial (part 1) appeared first on Coding Insight.


Viewing all articles
Browse latest Browse all 10

Trending Articles