Learning AngularJS day by day

I’ll be using AngularJS for a project at work, mainly using Mastering Web Application Development with AngularJS and This ebook.

Basic Concepts

Model

AngularJS models are plain, old JS objects. Models properties are not limited to be represented by primitive values(any valid JS object or array can be used). To expose a model to AngularJS you simply assign it to a $scope.

Controller

In AngularJS, a controller is just a regular JavaScript constructor which accepts a magic $scope parameter.
The primary responsibility of a controller is to initialize scope objects.

  • Providing initial model values
  • Augmenting $scope with UI-specific behavior/functions
  • A controller does the same job as the ng-init directive, but doing so in JS not HTML, when it comes to setting up initial model values.

Service & Dependency Injection

What are services:

  • Think of Service as the method of registering a constructor function/any singleton object that is created and managed by angular DI, with service dependency injection we can eliminate the new keyword
  • Services are singleton. All components of application works with single instance of the service.
  • Service instance gets created when application components need it.
  • Provides organization of shared data and functions across the application.

Service can be created in four different ways:

  • Using the service() method
  • Using the factory() method
  • Using the provider() method
  • Using the value() method
  • Using the constant() method

Using ervice()

Using the service() method uses the function constructor and it returns the object or instance of the function to work with
creating a calculator service

1
2
3
var CalculatorService = angular.module('CalculatorService', []).service('Calculator', function () {
this.square = function (a) { return a*a};
});
1
2
3
4
5
var myApp = angular.module('myApp', ['CalculatorService']);
myApp.controller('CalculatorController', function ($scope, Calculator) {
$scope.findSquare = function () {
$scope.answer = Calculator.square($scope.number);
}});
1
2
3
4
5
6
7
8
9
10
<div class="container">
<div>
<div ng-controller="CalculatorController">
Enter a number:
<input type="number" ng-model="number">
<button ng-click="findSquare()">Square</button>
<div></div>
</div>
</div>
</div>

Using factory()

create factory object and assign the methods to it.
Using the factory() method uses the returned value of the function. It returns the value of the function returned after the execution
Creating the service to reverse the string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
CalculatorService.factory('StringManipulation', function () {
var r= function reverse(s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
}
return{
reverseString: function reverseString(name) {
return r(name);
} } });
myApp.controller('CalculatorController', function ($scope, StringManipulation) {
$scope.findReverse = function(){$scope.reversename = StringManipulation.reverseString($scope.name);}
});
1
2
3
4
5
6
<div ng-controller="StringController">
Enter Name:
<input ng-model="name">
<button ng-click="findReverse()">Reverse Name</button>
<div></div>
</div>

The difference between creating a service using the service() method and the factory() method:

  • Using the service() method uses the function constructor and it returns the object or instance of the function to work with
  • Using the factory() method uses the returned value of the function. It returns the value of the function returned after the execution

(http://stackoverflow.com/questions/13762228/confused-about-service-vs-factory)

Well known services

$http and $q

$http in AngularJS is a core service for reading data from web servers. $http.get(url) is the function to use for reading server data.

1
2
3
4
5
var app = angular.module('myApp', []);
app.controller('planetController', function($scope, $http) {
$http.get("http://www.bogotobogo.com/AngularJS/files/httpRequest/planet.json")
.success(function(response) {$scope.names = response;});
});

$resource

$document

$window

$timeout & $interval

(http://stackoverflow.com/questions/14237070/using-setinterval-in-angularjs-factory)
(http://tutorials.jenkov.com/angularjs/timeout-interval.html#injecting-interval)
(http://plnkr.co/edit/?p=preview)

$parse

$cacheFactory

$filter

$apply

$watch & $watchcollection

(http://jsfiddle.net/TheSharpieOne/RA2j7/2/)

Directive

Simple program

I’ve build a simple one-page website using angular-ui and .NET framework.

1
2
3
4
5
6
7
8
9
AngularWeb
--content
--bootstrap.css
--scripts
--app
--studentCtrl.js
--angular.js
--Default.aspx
--Site.Master

studentCtrl.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
var app = angular.module('app', ['ngResource', 'ui.bootstrap']);
app.value('studentInfo', [
{ id: 1, name: 'Mahedee Hasan', credit: 20, semester: '8th' },
{ id: 2, name: 'Enamul Haque', credit: 15, semester: '7th' },
{ id: 2, name: 'Arefin Billah', credit: 15, semester: '6th' },
{ id: 3, name: 'Zahid Hasan', credit: 12, semester: '7th' },
{ id: 1, name: 'Mahedee Hasan', credit: 20, semester: '8th' },
{ id: 2, name: 'Enamul Haque', credit: 15, semester: '7th' },
{ id: 2, name: 'Arefin Billah', credit: 15, semester: '6th' },
{ id: 3, name: 'Zahid Hasan', credit: 12, semester: '7th' },
{ id: 1, name: 'Mahedee Hasan', credit: 20, semester: '8th' },
{ id: 2, name: 'Enamul Haque', credit: 15, semester: '7th' },
{ id: 2, name: 'Arefin Billah', credit: 15, semester: '6th' },
{ id: 3, name: 'Zahid Hasan', credit: 12, semester: '7th' }
]);
app.controller('studentsCtrl', function ($scope, studentInfo) {
$scope.studentInfo = studentInfo;
$scope.keys = null;
});
app.controller('sumController', function ($scope) {
$scope.data = {
sum: 1
}
$scope.increment = function(value) {
$scope.data.sum += value;
}
$scope.revert = function(value) {
$scope.data.sum -= value;
}
$scope.clear = function() {
$scope.data.sum = 0;
}
})
app.directive('myclick', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attr) {
var parsed = $parse(attr .myclick);
element.bind("click", function () {
alert("loading...");
scope.$apply(function () {
parsed(scope);
})
})
}
}
})

Default.aspx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AngularWeb.Default" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div class="page-header">
<h1> Test program
</div>
<div class="container" ng-controller="studentsCtrl" ng-app="app">
<input type="text" ng-model="keys" placeholder="Search..." type="text" class="form-control" />
<table class="table table-striped table-hover table-condensed">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Credit</th>
<th>Wow</th>
</tr>
</thead>
<tr ng-repeat="student in studentInfo | filter : keys">
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
<div ng-app="app" ng-controller="sumController" class="btn-group">
<h4>Current Value: </h4> <br/>
<label class="btn btn-primary" ng-click="increment(2)"> Add to current</label>
<label class="btn btn-primary" ng-click="revert(2)">Revert</label>
<label class="btn btn-primary" ng-click="clear()">Clear</label>
<label class="btn btn-primary" myclick="increment(2)">Try Directives</label>
<br/>
</div>
</div>
</asp:Content>

Site.Master

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="AngularWeb.Site" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
<link href="Content/bootstrap.css" rel="stylesheet" type="text/css" />
<script src="scripts/angular.js"></script>
<script src="scripts/angular-resource.min.js"></script>
<script src="scripts/ui-bootstrap-tpls-0.13.0.js"></script>
<script src="scripts/app/app.js"></script>
<script src="scripts/app/data.js"></script>
<script src="scripts/app/studentsCtrl.js"></script>
</body>
</html>


Useful Plugins

UI-Router

Angular-UI

Datatables