AngularJS

From sheep
Jump to navigation Jump to search

App

 <html ng-app="notesApp">
 
 angular.module('notesApp', [])

Services Object

function ItemObjectService() {
	var items = [
	{id: 1, label : 'Item 1'},...];
	this.list = function() {
		return items;
	};
	this.add = function(item) {
		items.push(item);
	};
}

.service('ItemObjectService', [ItemObjectService]
 // service - for classes OO style
);

Services functional

.factory('ItemService', function() {
	// factory - functional/return functoins/objects
        // no self/this as this is functional not object?
	var items = [
	{id: 1, label : 'Item 1'},...];
	return {
		list: function() {
			// Why not self.items or this.items?
			return items;
		},
		add: function(item) {
			items.push(item);
		}
	}
})

Promises

can chain:

$http.get("/foo").then(function(response) { }, function(errro) { } ).then(S, E).then(S, E)...

error handling propagates can put common error handling at the end.

$q service

  • var deferredObj = $q.defer() - create own promises
  • $q.deferredObj.resolve(successData) - resolve deferredObj with successData
  • $q.deferredObj.reject(failureData) - resolve deferredObj with failureData
  • $q.reject(rejectData) - from within a promise (success or failure) - continue to next error handler with rejectData

$http

can supply just url or put the url and method on the config and use $http(config)

  • $http.get(url, config)
  • $http.post(url, data, config)
  • $http.put(url, data, config)
  • $http(config)

config:

{
method
url
params [{key: 'value', key2: 'value2'}] // value objects converted to json
data {}
headers {'Content-Type': 'text/csv'}
xsrfHeaderName - cross site request forgery 
xsffCookieName - name of cookie in xsrf handshake
cache : true/false or cache object - if true angular caches responses
transformRequest: function(data, headers){} 
transformResponse: 
timeout: // time or promise object that on reject timesout the call
withCredentials: true/false
}