You are on page 1of 11

Problem: HTML is good for static content.

For dynamic content, a DOM manipulation library is


required.
Solution: AngularJS extends HTML and make it dynamic using declarative syntax.
Great for Single Page Applications (SPA) and SCRUD applications.
Uses MVW (Model-View-Whatever) framework on the UI.
Separates HTML DOM references from the JavaScript
Provides tools for UI testing.
Cross-browser compatible.
Great third party modules like AngularUI.

MVC: or MVVM or whatever (MVW).


Model: The Model is simply the data in the application and is just plain old JavaScript objects.Modal
represents business data. The view is a projection of the model at any given time.
View: The View is the HTML that exists after AngularJS has parsed and compiled the
HTML to include rendered markup(directives) and bindings. You can think of the view as
simply an instant projection of your model.
It should update itself whenever the underlying data model changes. In AngularJS the view reads
model data from the $scope. So the $scope object is where the Controller and the View share data.
Scope is nothing but an object that Glues the View with Controller. They hold the Model
data that we need to pass to view. Scope uses Angulars two-way data binding to bind
model data to view.
$scope is an object that links Controller to the View. It is controllers responsibility to
initialize the data that the view needs to display. This is done by making changes to
$scope.
ViewModel: A ViewModel is an object that provides specific data and methods to
maintain specific views. Binds view to the model.
Controller: In AngularJS, controller is simply formed by JavaScript functions. It controls
how view and model will communicate. Controllers are nothing but plain JavaScript
functions which are bound to a particular scope. Controllers should only contain
bindings and logic needed for a single view. Controller handles inputs, calls the
business code and shares data with view via $scope. In AngularJS, the business logic is
performed inside a service and injected into the controller. The controller uses the
services to obtain data and sets it on the $scope, so it is just aware of the $scope and
not the view. When a Controller is attached to the DOM via the ng-controller directive, Angular
will instantiate a new Controller object, using the specified Controller's constructor function. A
new child scope will be created and made available as an injectable parameter to the
Controller's constructor function as $scope.
Use controllers to:
Set up the initial state of the $scope object.

Add behavior to the $scope object.

Module: A container for the different Angular components: controllers, services,


factories, filters, directives etc.

Defining a module:

( function(){
'use strict';
//creates a module with the name 'app'

})();

//the empty array is the list of the other modules that app module depends on.
angular.module('app', []);
//defining a module with dependencies
angular.module('anotherApp', ['ngRoute', 'ngMessages']);

Using a module in the HTML:

<html ng-app="app">
----

</html>

Module Creation versus Retrieval


//creating a new module 'app' and overwrite any existing app module
angular.module('app', []);
//or, get access to an existing app module and define a component
angular.module('app').controller('MainController', MainControllerFn);

Templates. the template consists of HTML, CSS, and Angular directives contained in just
one HTML file. templates are written with HTML that contains Angular-specific elements and
attributes. Angular combines the template with information from the model and controller to
render the dynamic view that a user sees in the browser.
Templates: HTML that contains Angular-specific elements and attributes.

Inline Templates: The HTML that is already the part of page.

<div ng-controller="MainController as mainVm">


<input type="text" ng-model="mainVm.myName" placeholder="Enter Your
Name" />

<p>{{mainVm.myName}}</p>

</div>
External Templates: The HTML that can be fetched from the server.

<div ng-include="'path/to/someTemplate.html'"></div>

Internal Templates:The script tag containing the template does not need to be included in

the head of the document, but it must be below the ng-app definition.

<script type="text/ng-template" id="someTemplate">


<p>{{mainVm.myName}}</p>
</script>
<body>
<div ng-controller="MainController as mainVm">
<div ng-include="'someTemplate'"></div>
</div>
</body>

Data-binding in Angular apps is the automatic synchronization of data between the model and
view components. The way that Angular implements data-binding lets you treat the model as the
single-source-of-truth in your application. The view is a projection of the model at all times. When
the model changes, the view reflects the change, and vice versa. First the template (which is the
uncompiled HTML along with any additional markup or directives) is compiled on the browser. The
compilation step produces a live view. Any changes to the view are immediately reflected in the
model, and any changes in the model are propagated to the view. The model is the single-sourceof-truth for the application state, greatly simplifying the programming model for the developer. You
can think of the view as simply an instant projection of your model.

Dependency Injection: Providing the objects that an object needs (its dependencies) instead of
having it construct them itself. Useful technique for testing, since it allows dependencies to be
mocked or stubbed out.

Identifying Dependencies

Example

angular.module('app').controller('MainController', MainControllerFn);
function MainControllerFn ($rootScope, $http) {
var mainVm = this;
mainVm.name = '';
$http.get({method: 'GET', url: 'abc.com'});
$rootScope.someProp = "SomeValue";
}

After Minification

angular.module('app').controller('MainController', e);
function e (a, b) {
var d = this;
d.name = '';
b.get({method: 'GET', url: 'abc.com'});
a.someProp = "SomeValue";
}
//Error: [$injector:unpr] Unknown provider: aProvider <- a

Becomes impossible for Angular to detect and inject right dependencies.


Solutions:
o $inject Property Annotation:

angular.module('app').controller('MainController', MainControllerFn);
MainControllerFn.$inject = ['$rootScope', '$http'];
//order in $inject array must match order of parameters
function MainControllerFn ($rootScope, $http) {
var mainVm = this;
mainVm.name = '';
$http.get({method: 'GET', url: 'abc.com'});
$rootScope.someProp = "SomeValue";
}

In-line dependencies:
angular.module('app').controller('MainController',
['$rootScope', '$http', MainControllerFn]);
function MainControllerFn ($rootScope, $http) {
var mainVm = this;
$http.get({method: 'GET', url: 'abc.com'});
$rootScope.someProp = "SomeValue";
}

Angular Expressions {{ JavaScript-like code snippet }}: unit of code that evaluates to a
value. Denotes a binding and tells Angular that it should evaluate an expression and insert the
result into the DOM in place of the binding. This binding can handle continuous updates whenever
the result of the expression changes.

ng-app directive: This directive specifies that Angular should consider html element to be the
root element of the app. When angular.js loads for the first time, it looks for the ng-app
directive in the HTML page and bootstrap the app.
Use ng-controller directive to attach a controller to that particular part of DOM.

(function(){
angular.module('app', []);
angular.module('app').controller('GreetingController', GreetingControllerFn);
function GreetingControllerFn () {
var greetingVm = this;
greetingVm.greeting = 'Hola!'; //add a property on the child scope
}
})();
<div ng-controller="GreetingController as greetingVm">{{ greetingVm.greeting }}</div>
ngRepeat: Repeats a template once per item from a collection.

<p ng-repeat="item in vm.myArray">{{item}}</p>


<!-- over Object-->
<p ng-repeat="(key,val) in vm.myObject">{{val.property}}</p>

ngInit: Initialize the property on scope.

<div ng-init="vm.someProp = 'value goes here'">


</div>
ngChange: Evaluate the given expression when the user changes the input.
<input type="checkbox" ng-model="vm.confirmed" ng-change="vm.change()" />

ngClick: Specify custom behavior when an element is clicked.

<button ng-click="vm.count = vm.count + 1" ng-init="vm.count=0">


Increment
</button>
count: {{vm.count}}

ngClass: Dynamically set CSS classes on an HTML element by databinding an expression

<p ng-class="'some-class' + '-apply'">Hello Angular</p>


<p ng-class="{'myClass1': vm.sample.prop1, 'myClass2': vm.sample.prop2,
'myClass3': vm.sample.prop3}">
Hello Angular
</p>
<p ng-class="{true: 'myClass1 myClass2', false: ''}[vm.sample.prop1]">Hello
Angular</p>
<p ng-class="{'Pending': 'pending-class',
'Submitted': 'submitted-class',
'Waiting': 'waiting-class'}[vm.status]">Reservation Status</p>
ngShow: Shows or hides the given HTML element based on the expression provided to
the ngShow attribute
<div ng-show="vm.shouldShow"></div>
ngHide: Shows or hides the given HTML element based on the expression provided to
the ngHide attribute
<div ng-hide="vm.shouldHide"></div>
ngIf: Removes or recreates a portion of the DOM tree based on an ngIf expression.
HTML
<div ng-if="vm.shouldPresent"></div>

ngHref:
<a href="http://www.gravatar.com/avatar/{{hash}}"/>

<a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>

ngSrc: <img src="{{vm.profilePicUrl}}"/>

<img ng-src="{{vm.profilePicUrl}}"/>

ng-model Directive: Links the HTML element and the model. Any changes to the control update
the data in your model, and when you change the model it updates the control. TWO WAY DATA
BINDING

$rootScope: Refers to the app's root scope (Every app has a single root scopeOther
scopes are descendant scopes of the root scope.

//someProp is available across all the components of a module like


//controllers, services, filter, directives etc.
$rootScope.someProp = 'SomeVal';

Services
Angular services are substitutable objects that are wired together using dependency injection (DI).
You can use services to share code and data across the app.
Angular services are:
Lazily instantiated Angular Services are lazily initialized (initiates only when its needed).Angular
only instantiates a service when an application component depends on it.
Singletons Angular Services are singletons per Angular module. Each component dependent on a
service gets a reference to the single instance generated by the service factory.
Angular offers several useful services (like $http), but for most applications you'll also want
to create your own. To use an Angular service, you add it as a dependency for the component
(controller, service, filter or directive) that depends on the service. Angular's dependency
injection subsystem takes care of the rest. The service factory function generates the single
object or function that represents the service to the rest of the application. The object or function
returned by the service is injected into any component (controller, service, filter or directive) that
specifies a dependency on the service.

Application developers are free to define their own services by registering the service's name
and service factory function, with an Angular module.

//Inject the service (not its object) into the


//component (controller, service, filter, directive)
angular.module('app').controller('MainController', MainControllerFn);
MainControllerFn.$inject = ['$rootScope', '$http', '$routeParams' ]
function MainControllerFn ($rootScope, $http, $routeParams) {
var mainVm = this;
mainVm.name = '';
$http.get(....);
$rootScope.someProp = "SomeValue";
}

Creating a Service or Factory:

angular.module('app', []);

//create a factory

angular.module('app').factory('myFactory', myFactory);
function myFactory() {
var self = {}, localVar;
//add exposable properties on self
self.name = 'This is a factory';
return self;
}

//create a service
angular.module('app').service('myService', myService);
function myService() {
var localVar = 1;
//add exposable properties on this
this.name = 'This is a Service';
}
angular.module('app', []);

//Creating a service with dependencies


angular.module('app').service('myService', myService);
function myService($http, $location) {
//use dependencies here
this.name = 'Service';
}

//Injecting the service or factory


angular.module('app').controller('MainController', MainControllerFn);
function MainControllerFn ($rootScope, $http, myService) {
var mainVm = this;
$http.get(....);
$rootScope.someProp = "SomeValue";
console.log(myService.name);
}

$http: Communicate with the remote HTTP servers via the browser's
XMLHttpRequest object or via JSONP.

$http.get('/someUrl', [config]).then(successCallback);
$http.post('/someUrl', data, [config]).then(successCallback);

$http.put('/someUrl', data, [config]).then(successCallback);


$http.delete('/someUrl', [config]).then(successCallback);

//JSONP request must contain JSON_CALLBACK as the callback value in the URL
$http.jsonp('www.someotherdomain.com/someUrl' + '?callback=JSON_CALLBACK',
[config]).then(successCallback);
configObj ==> {
method
: 'GET' | 'POST' | 'PUT' | 'DELETE' etc.,
url
: '/someurl',
params
: 'string' | object /*queryString*/,
data
: 'string' | object /*post*/
}
response ==> {
data
: {string|Object} The response body transformed with the transform

functions.
status : {number} HTTP status code of the response.
headers : {function([headerName])} Header getter function.
config : {Object} The configuration object that was used to generate the

request.
statusText: {string} HTTP status text of the response.
}

The Promise object is used for deferred and asynchronous computations.


A Promise represents an operation that hasn't completed yet, but is expected in the future.
Part of ES2016 Spec now. Promise on MDN
Angular promise service $q is based on Kris Kowal's Q
The $http service is based on the deferred/promise APIs exposed by the $q service.
An Angular service should be used for delegating HTTP requests and responses.

Routing helps you in dividing your application in logical views and bind
different views to Controllers.
Allows to navigate among the views and also store this navigation in the
browser history.

SPA can still be built without url-based routing, but as soon as you refresh
the page, it will land on the first view. No browser back-forward button
support either.

You might also like