Module examples
angular.module('app', []);
angular.module('app', ['ngRoute']);
Router examples
angular
.module('app')
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('root', {
url: "/",
templateUrl: 'document/document.html',
controller: 'DocumentCtrl',
controllerAs: 'documentVm'
})
.state('thisroute', {
url: "/this/:skuId",
templateUrl: 'templates/this.html',
controller: 'ThisCtrl',
controllerAs: 'thisVm'
});
});
angular
.module('shopApp')
.config(['localStorageServiceProvider', function(localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('app')
.setDefaultToCookie(true);
}]);
Interceptor example (used in the same file as the router, typically)
angular
.module('app')
.service('httpInterceptor', function($q, $location, $window, alertService) {
var service = this;
service.responseError = function(response) {
if (response.status == 400) {
//alertService.addAlert({ type: "system", msg: "Bad Request", status: "danger" });
//$location.path("/signin");
}
else if (response.status == 401) {
// Reloading the page will either just get the session ID and carry on, or divert to the login page
$window.location.reload();
}
return $q.reject(response);
};
})
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
}]);
Constants examples
angular
.module('app')
.constant('paths', {
DOCUMENT_API_URL: '/api/v1/documents',
USER_API_URL: '/api/v1/user'
})
.constant('itemTypes', { SUBSCRIPTION: 'subscription' });
// Then inject "paths" or "itemTypes" into Controller etc.
Values examples
angular
.module('app')
.value('environment', { dummy: false });
// Then inject "environment" into Controller etc.
Controller examples
(function() {
'use strict';
angular
.module('app')
.controller("ThisCtrl", ThisCtrl);
ThisCtrl.$inject = ['$rootScope', '$scope', '$filter', 'myService'];
function ThisCtrl($rootScope, $scope, $filter, myService) {
var thisVm = this;
// Initialise the controller and scope variables
(function () {
// Get the checkout document
documentService.getData("type").then(function (response) {
if (response.status == 200) {
thisVm.data = response.data;
$rootScope.$broadcast('new-data', { "extra": 12345678 });
}
});
})();
}
Directive examples
angular
.module('app')
.directive('logo', logo);
logo.$inject = [];
function logo() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
var theme = scope.$eval(attrs.src);
element.replaceWith('<img src="/img/skins/' + theme + '/brand-logo.png" />');
}
};
}
// <logo src="xxx" />
angular
.module('app')
.directive('doSomething', doSomething);
doSomething.$inject = ['$location', 'trackingService', 'theService'];
function doSomething($location, trackingService, theService) {
return {
restrict: 'AE', // A, E, C
templateUrl: 'shared/do-something-template.html',
scope: {
ngModel: '=',
replace: true,
layout: '@'
},
controller: function ($scope, $attrs) {
var somethingControllerVm = this;
somethingControllerVm.attrs = $attrs;
somethingControllerVm.item = $scope.ngModel;
function someFunction() {
trackingService.log("shop", "category selected", singleCategoryVm.item);
$location.path("/store/" + singleCategoryVm.item.id);
}
},
controllerAs: 'somethingControllerVm'
}
}
// <do-something ng-model="thisVm.data" layout="with-sidebar" />
- scope can be true, rather than an object, to create a child scope. Otherwise it'll use the parent's scope
- “Am I just doing template and scope things?” – goes into controller
“Am I adding some coolbeans jquery library?” – goes in link
- < is for one-way binding.
- @ binding is for passing strings. These strings support {{}} expressions for interpolated values.
- = binding is for two-way model binding. The model in parent scope is linked to the model in the directive's isolated scope.
- & binding is for passing a method into your directive's scope so that it can be called within your directive.
Services examples
function () {
angular
.module('app')
.factory('dataService', dataService);
dataService.$inject = ['$http', '$q', 'paths'];
function dataService($http, $q, paths) {
var dataService = {};
dataService.getData = getData;
dataService.getDifferentData = getDifferentData;
dataService.getLocalDataFile = getLocalDataFile;
function getData(documentId) {
return $q(function (resolve, reject) {
getRemoteData(documentId).then(function (response) {
if (response.status == 200 && response.data) {
//processDocument(response.data);
resolve(response);
}
else {
//reject(false);
resolve(response);
}
}, function (response) { reject(); })
});
}
function getDifferentData(documentId) {
var documentUrl = angular.isDefined(documentId) && documentId ? "?id=" + documentId : "";
var request = $http({
method: "GET",
url: paths.DOCUMENT_API_URL + documentUrl,
timeout: 5000
});
return (request.then(
function (response) {
processDocument(response.data);
return( response );
},
function ( response ) {
return( response );
}
));
}
function getLocalDataFile(documentId) {
var request = $http({
method: "GET",
url: "data/document-" + documentId + ".json"
});
return (request.then(
function (response) {
processDocument(response.data);
return( response );
},
function ( response ) {
return( response );
}
));
}
}
Filters examples
angular
.module('app')
.filter('parseCurrency', function () {
return function (text, target) {
return text.replace(new RegExp("%curr%", "g"), target);
};
});
/* Will return safe HTML to output to the view */
angular
.module('app')
.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
angular
.module('app')
.filter('trust', function($sce) { return $sce.trustAsResourceUrl; });
angular
.module('app')
.filter('inCollection', filterItems);
filterItems.$inject = ['itemsService'];
function filterItems(itemsService) {
return function (items) {
var filtered = [], itemStatus;
if (items) {
for (var itemLoop = 0, len = items.length; itemLoop < len; itemLoop++) {
itemStatus = itemsService.itemsGetStatus(items[itemLoop]);
if (itemStatus == 0 || itemStatus == 4 || itemStatus == 5) { // Eligible
filtered.push(items[itemLoop]);
}
}
}
return filtered;
}
}