Created
January 17, 2014 08:35
-
-
Save yagopv/8470162 to your computer and use it in GitHub Desktop.
Angular Snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Modules | |
var shoppingModule = angular.module('ShoppingModule', ['moduleDependency1', 'moduleDependency2']); | |
// Controllers | |
shoppingModule.controller("HomeController", ["$scope", "$resource", | |
function($scope, $resource) { | |
} | |
]); | |
// Services | |
shoppingModule.factory('Items', function() { | |
var items = {}; | |
items.query = function() { | |
// In real apps, we'd pull this data from the server... | |
return [ | |
{title: 'Paint pots', description: 'Pots full of paint', price: 3.95}, | |
{title: 'Polka dots', description: 'Dots with polka, price: 2.95}, | |
{title: 'Pebbles', description: 'Just little rocks', price: 6.95} | |
]; | |
}; | |
return items; | |
}); | |
// Filters | |
homeModule.filter('titleCase', function() { | |
var titleCaseFilter = function(input) { | |
var words = input.split(' '); | |
for (var i = 0; i < words.length; i++) { | |
words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1); | |
} | |
return words.join(' '); | |
}; | |
return titleCaseFilter; | |
}); | |
<body ng-app='HomeModule' ng-controller="HomeController"> | |
<h1>{{pageHeading | titleCase}}</h1> | |
</body> | |
function HomeController($scope) { | |
$scope.pageHeading = 'behold the majesty of your page title'; | |
} | |
// Routes | |
someModule.config(function($routeProvider) { | |
$routeProvider. | |
when('url', {controller:aController, templateUrl:'/path/to/tempate'}). | |
when(...other mappings for your app...). | |
… | |
otherwise(...what to do if nothing else matches...); | |
)}; | |
<div ng-view></div> | |
// &http | |
function ShoppingController($scope, $http) { | |
$http.get('/products').success(function(data, status, headers, config) { | |
$scope.items = data; | |
}); | |
} | |
// Directives | |
appModule.directive('ngbkFocus', function() { | |
return { | |
link: function(scope, element, attrs, controller) { | |
element[0].focus(); | |
} | |
}; | |
}); | |
// Tip. ng-repeat compile called once. Link called once per item | |
<div ng-repeat='thing in things'> | |
<my-widget config='thing'></my-widget> | |
</div> | |
var myModule = angular.module(...); | |
myModule.directive('namespaceDirectiveName', function factory(injectables) { | |
var directiveDefinitionObject = { | |
restrict: string, // E (Element) A (Attr. Default) C (Class) M (Comment) | |
priority: number, // 0 Min -- N Max (Default 0) | |
template: string, // inline template | |
templateUrl: string, // AJAX template | |
replace: bool, // Replace or append | |
transclude: bool, // Send content of the original element to the template. Can render it via ng-transclude | |
scope: bool or object, | |
// false => parent scope, | |
// true => new scope shared with other directives in the DOM element, | |
// or object if creating a isolated scope | |
// If selecting isolated then you don´t have access to the parent scope, but you can pass parameters from it | |
controller: function controllerConstructor($scope, $element, $attrs, $transclude), | |
require: string, | |
link: function postLink(scope, iElement, iAttrs) { ... }, | |
compile: function compile(tElement, tAttrs, transclude) { | |
return { | |
pre: function preLink(scope, iElement, iAttrs, controller) { ... }, | |
post: function postLink(scope, iElement, iAttrs, controller) { ... } | |
} | |
}; | |
return directiveDefinitionObject; | |
}); | |
//Directive scope | |
/* | |
@ Pass this attribute as a string. You can also data bind values from enclosing scopes by using interpolation {{}} in the | |
attribute value. | |
= Data bind this property with a property in your directive’s parent scope. | |
& Pass in a function from the parent scope to be called later. | |
*/ | |
// Inline template in teh same page and retrieved via templateurl. Not waiting for download | |
<script type='text/ng-template' id='helloTemplateInline.html'> | |
<div>Hi there</div> | |
</script> | |
// Resource definition | |
myAppModule.factory('CreditCard', ['$resource', function($resource) { | |
return $resource('/user/:userId/card/:cardId', | |
{userId: 123, cardId: '@id'}, | |
{charge: {method:'POST', params:{charge:true}, isArray:false}); | |
}]); | |
// Resource definition with $http | |
myAppModule.factory('CreditCard', ['$http', function($http) { | |
var baseUrl = '/user/123/card'; | |
return { | |
get: function(cardId) { | |
return $http.get(baseUrl + '/' + cardId); | |
}, | |
save: function(card) { | |
var url = card.id ? baseUrl + '/' + card.id : baseUrl; | |
return $http.post(url, card); | |
}, | |
query: function() { | |
return $http.get(baseUrl); | |
}, | |
charge: function(card) { | |
return $http.post(baseUrl + '/' + card.id, card, {params: {charge: true}}); | |
} | |
}; | |
}]); | |
//Interceptor for http requests | |
// register the interceptor as a service | |
myModule.factory('myInterceptor', function($q, notifyService, errorLog) { | |
// Creating service with $http and promises | |
var services = angular.module('guthub.services', ['ngResource']); | |
services.factory('Recipe', ['$resource', | |
function($resource) { | |
return $resource('/recipes/:id', {id: '@id'}); | |
} | |
]); | |
services.factory('MultiRecipeLoader', ['Recipe', '$q', | |
function(Recipe, $q) { | |
return function() { | |
var delay = $q.defer(); | |
Recipe.query(function(recipes) { | |
delay.resolve(recipes); | |
}, function() { | |
delay.reject('Unable to fetch recipes'); | |
}); | |
return delay.promise; | |
}; | |
}]); | |
return function(promise) { | |
return promise.then(function(response) { | |
// Do nothing | |
return response; | |
}, function(response) { | |
// My notify service updates the UI with the error message | |
notifyService(response); | |
// Also log it in the console for debug purposes | |
errorLog(response); | |
return $q.reject(response); | |
}); | |
} | |
}); | |
$httpProvider.responseInterceptors.push('myInterceptor'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment