On Github wrozka / angular-workshop-services
Paweł Pierzchała @zwrozka
Controller definition
angular.module('workshops.timeline') .controller('TimelineController', ['$scope', controller]);
Dependency Injection
var controller = function($scope, $timeout, timelineService) { }
Dependencies types
Values & constants
provide.value('a', 123); function Controller(a) { expect(a).toEqual(123); }
Factories
provide.factory('b', function(a) { return a*2; }); function Controller(b) { expect(b).toEqual(246); }
Objects
function Greeter(a) { this.greet = function() { return 'Hello ' + a; } } provide.factory('greeter', function(a) { return new Greeter(a); }); function Controller(greeter) { expect(greeter.greet()).toEqual('Hello 123'); }
Services
provide.factory('greeter', function(a) { return new Greeter(a); });
provider.service('greeter', Greeter);
Providers
provide.provider('greeter2', function() { var salutation = 'Hello'; this.setSalutation = function(s) { salutation = s; } function Greeter(a) { this.greet = function() { return salutation + ' ' + a; } } this.$get = function(a) { return new Greeter(a); }; });
Providers
angular.module('abc', []).configure(function(greeter2Provider) { greeter2Provider.setSalutation('Halo'); }); function Controller(greeter2) { expect(greeter.greet()).toEqual('Halo 123'); }
$provider
$injector
$injector.invoke(function(greeter) { greeter.greet(); })
greeter = $injector.get('greeter');
Dependency annotation
provider.service('greeter', ['$scope', Greeter]);
Greeter.$inject = ['$scope']; provider.service('greeter', Greeter);
Controllers, Directives & Filters
$controller, $directive, $filter
Angular module
angular.module('workshops.timeline')
Angular dependencies
angular.module('workshops.timeline', ['ng', 'Restangular', 'workshop.directives.form'])
Modularization practices
Testing
describe("A suite", function() { it("contains spec with an expectation", function() { expect(true).toBe(true); }); });
describe('messages creation', function() { it('posts new messages to the backend', inject(function($httpBackend) { })); });
describe('timelineService', function() { beforeEach(module('workshops.timeline')) });
beforeEach(inject(function($httpBackend) { $httpBackend.whenGET('/api/users') .respond(200, [{id: 1, login: 'alice'}]); }));
it('posts new messages to the backend', inject(function($controller) { var scope = {}; $controller('TimelineController', {'scope': scope}); expect(scope.users).toEqual([]); }));
npm install -g karma
var users = Restangular.all('/api/users').getList();
Create a timelineService
Test it!
Test integration beetwen the controller and the service
Routing
GET '/api/wall_items' POST '/api/wall_items' GET '/api/users'