Angularjs Notes
Angularjs Notes
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']);
<html ng-app="app">
----
</html>
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.
<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.
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
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.
ngHref:
<a href="http://www.gravatar.com/avatar/{{hash}}"/>
<a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
<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.
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.
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', []);
$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);
//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.
}
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.