...
Code Block |
---|
|
// Implicit
angular.module('myApp')
.controller('MyCtrl', function($scope, myService) {
// Do something awesome
});
// Explicit
var MyCtrl = function(some$scope, someService) {
// Do something awesome
}
MyCtrl.$inject = ['$scope', 'myService'];
// Inline
angular.module('myApp')
.controller('MyCtrl', ['$scope', 'myService',
function($scope, myService) {
// Do something awesome
}]);
|
Building
TODO: add content here
Testing
...
Routing Services
- The AngularJS framework has a built-in $route service that can be configured to handle route transitions in single-page web applications
- Routes can be defined during the application's configuration phase using the $routeProvider service
Code Block |
---|
|
angular.module("MyApp", []).
config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/persons", {
templateUrl: "partials/index.html"
})
.when("/persons/:id", { // In ShowCtrl, id is available via $routeParams.id
templateUrl: "partials/show.html",
controller: "ShowCtrl"
})
.when("/login", {
templateUrl: "partials/login.html",
controller: "LoginCtrl"
})
.when("/help", {
templateUrl: "partials/help.html"
})
.otherwise( {
redirectTo: "/persons"
});
});
|
Testing
Unit Test with Jasmine
- Jasmine is a Behavior-driven development framework for testing JavaScript code
- Karma supports multiple testing frameworks, but the default option is Jasmine
Anatomy of a Jasmine Test
Code Block |
---|
|
describe('hello World test', function () {
var greeter;
beforeEach(function () {
greeter = new Greeter();
});
it('should say hello to the World', function () {
expect(greeter.say('World')).toEqual('Hello, World!');
});
});
|
- The describe function, describes a feature of an application. It acts as an aggregating container for individual tests (test suite)
- Code contained in the beforeEach block will get executed before each individual test
- The test itself is located inside the it function. The idea is to exercise one particular aspect of a feature in one test
Testing AngularJS Objects with Jasmine
We need to ensure that a proper AngularJS module is initialized and the whole DI machinery is configured
Code Block |
---|
|
describe('UserService Service', function() {
// indicate that services from a given module should be prepared for the test
// $injector should be created for a given module (and all the dependent modules).
beforeEach(module('services'));
var userService;
beforeEach(inject(function(UserService) { // inject UserService and assign to local variable
userService = UserService;
}));
// execute test
it('should have user', function() {
expect(userService.getUser()).toEqual('testUser');
});
});
|
Best Practices
There are some great resources available on this topic already. Instead of duplicating all of them, here are some links to review.
...