When developing a project, it’s always good to have the same and consistent coding styles. Based on the AngularJS styleguide. I wrote something that I think is practical. With both production and tests. It’s a good example or guides to follow when writing “things” in AngularJS 1.4.x. If you want to know why, refer to AngularJS styleguide.
1, Controllers
# naming
use camelCase for the js file name with “Controller” suffix: loginController.js
use camelCase with first letter capitalized for defining controller. E.g. LoginController
# Always use “controllerAs”
1
<div ng-controller="LoginController as login"></div>
describe('login directive', function() { var compile, $rootScope;
// Load the myApp module, which contains the directive beforeEach(module('app'));
// Store references to $rootScope and $compile // so they are available to all tests in this describe block beforeEach(inject(function(_$compile_, _$rootScope_){ // The injector unwraps the underscores (_) from around the parameter names when matching compile = _$compile_; rootScope = _$rootScope_; }));
it('should show login htmls', function() { // Compile a piece of HTML containing the directive var element = compile("<login></login>")(rootScope); // fire all the watches, so the scope expression {{1 + 1}} will be evaluated $rootScope.$digest(); // Check that the compiled element contains the templated content expect(element.html()).toContain("lidless, wreathed in flame, 2 times"); }); });
describe('MyController', function() { var $httpBackend, $rootScope, createController, authRequestHandler;
// Set up the module beforeEach(module('MyApp'));
beforeEach(inject(function($injector) { // Set up the mock http service responses $httpBackend = $injector.get('$httpBackend'); // backend definition common for all tests authRequestHandler = $httpBackend.when('GET', '/auth.py') .respond({userId: 'userX'}, {'A-Token': 'xxx'});
// Get hold of a scope (i.e. the root scope) $rootScope = $injector.get('$rootScope'); // The $controller service is used to create instances of controllers var $controller = $injector.get('$controller');