Slide 1

Slide 1 text

David Cramer twitter.com/zeeg Flask and Angular

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

In a nutshell, it's MAGIC

Slide 4

Slide 4 text

{{ post.body }}

Slide 5

Slide 5 text

What are we doing?

Slide 6

Slide 6 text

๏ A LOT of code (mostly JS + Angular) ๏ A fairly ugly ”modern” blog ๏ API-driven backend, client-driven frontend ๏ Basic dependency management organization ๏ Testing principles (in Flask and Angular)

Slide 7

Slide 7 text

Questions? Interrupt Me!

Slide 8

Slide 8 text

Bootstrapping

Slide 9

Slide 9 text

☑ Python 2.6+

Slide 10

Slide 10 text

☑ Node.js (NPM)

Slide 11

Slide 11 text

☑ Virtualenv

Slide 12

Slide 12 text

# git clone https://github.com/dcramer/ pyconsg-tutorial-bootstrap.git http://git.io/pjNCxA

Slide 13

Slide 13 text

$ less README.rst Setup the environment: virtualenv ./env source ./env/bin/activate Install dependencies: # python pip install -e . # node (tools) npm install # bower (js 3rd party) node_modules/.bin/bower install

Slide 14

Slide 14 text

$ less setup.py # ... tests_require = [ 'pytest>=2.5.0,<2.6.0', ] install_requires = [ 'blinker>=1.3,<1.4', 'flask>=0.10.1,<0.11.0', 'flask-restful>=0.2.12,<0.3.0', 'flask-sqlalchemy>=1.0,<1.1', 'sqlalchemy==0.9.4', ] # ...

Slide 15

Slide 15 text

$ less package.json { "name": "pyconsg-tutorial-bootstrap", "private": true, "version": "0.0.0", "devDependencies": { "bower": "^1.3.1", "karma": "~0.10" }, "scripts": { "postinstall": "bower install", "pretest": "npm install", "test": "karma start tests/karma.conf.js" } }

Slide 16

Slide 16 text

$ less bower.json { "name": "pyconsg-tutorial-bootstrap", "version": "0.0.0", "ignore": [ "**/.*", "node_modules", "static/vendor", "tests" ], "dependencies": { "angular": "~1.2.17", "bootstrap": "~3.1.1" }, "resolutions": { "angular": "1.2.17" } }

Slide 17

Slide 17 text

$ less .bowerrc { "directory": "static/vendor" }

Slide 18

Slide 18 text

Config blog/config.py

Slide 19

Slide 19 text

$ less blog/config.py # ... def create_app(**config): app = Flask( __name__, static_folder=os.path.join(PROJECT_ROOT, 'static'), template_folder=os.path.join(PROJECT_ROOT, 'templates'), ) app.config['INDUCE_API_DELAY'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/blog.db' app.config['DEBUG'] = True app.config.update(config) db.init_app(app) configure_api_routes(app) configure_web_routes(app) return app

Slide 20

Slide 20 text

$ less blog/config.py # ... def configure_web_routes(app): from .web.index import IndexView app.add_url_rule( '/', view_func=IndexView.as_view('index'))

Slide 21

Slide 21 text

$ less blog/config.py # ... def configure_api_routes(app): from .api.post_details import PostDetailsResource from .api.post_index import PostIndexResource api.add_resource(PostIndexResource, '/posts/') api.add_resource(PostDetailsResource, '/posts//') api.init_app(app)

Slide 22

Slide 22 text

Data Models blog/models/*

Slide 23

Slide 23 text

$ less blog/models/post.py from datetime import datetime from blog.config import db class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80)) body = db.Column(db.Text) pub_date = db.Column(db.DateTime)

Slide 24

Slide 24 text

REST API blog/api/*

Slide 25

Slide 25 text

$ less blog/api/post_index.py from blog.api.base import Resource class PostIndexResource(Resource): def get(self): """ Return a list of posts. """ def post(self): """ Create a new post. """

Slide 26

Slide 26 text

$ less blog/api/post_details.py from blog.api.base import Resource class PostDetailsResource(Resource): def get(self, post_id): """ Return information about a given post. """ def post(self, post_id): """ Edit an existing post. """

Slide 27

Slide 27 text

Base Layout templates/index.html

Slide 28

Slide 28 text

$ less templates/index.html Blog <script src="{{ url_for('static', filename='js/app.js') }}"/> </head> <body ng-app="blog"> <section class="container"> <header> <h1><a href="/#/">My Blog</a></h1> </header> <section ng-view></section> <footer>&copy; My Blog</footer> </section> </body> </html>

Slide 29

Slide 29 text

Client Application static/js/app.js

Slide 30

Slide 30 text

$ less static/js/app.js 'use strict'; angular.module('blog', []).config(function() { // TODO: Initialize routes/general application config here });

Slide 31

Slide 31 text

Python Test Config tests/conftest.py

Slide 32

Slide 32 text

@pytest.fixture(scope='session') def app(request): app = create_app( SQLALCHEMY_DATABASE_URI='sqlite:///', INDUCE_API_DELAY=False, ) app_context = app.test_request_context() app_context.push() return app

Slide 33

Slide 33 text

@pytest.fixture(autouse=True) def setup_db(request, app): db.create_all() request.addfinalizer(db.drop_all) @pytest.fixture(autouse=True) def db_session(request): request.addfinalizer(db.session.remove)

Slide 34

Slide 34 text

@pytest.fixture(scope='session') def client(app): return app.test_client()

Slide 35

Slide 35 text

Fixtures are automatic Dependency Injection

Slide 36

Slide 36 text

$ py.test tests/

Slide 37

Slide 37 text

============================= test session starts ============================== platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2 collected 1 items tests/python/api/test_post_index.py F =================================== FAILURES =================================== __________________________________ test_list ___________________________________ tests/python/api/test_post_index.py:31: in test_list > assert len(data) == 2 E TypeError: object of type 'NoneType' has no len() =========================== 1 failed in 0.11 seconds ==========================

Slide 38

Slide 38 text

JavaScript Test Config tests/karma.conf.js

Slide 39

Slide 39 text

module.exports = function(config){ config.set({ basePath: '../', files: [ 'static/vendor/angular/angular.js', // 'static/vendor/angular-route/angular-route.js', // 'static/vendor/angular-mocks/angular-mocks.js', 'static/js/**/*.js', 'tests/js/**/*.js' ], autoWatch: true, frameworks: ['jasmine'], browsers: ['Chrome'], plugins: [ 'karma-chrome-launcher', 'karma-jasmine' ] }); };

Slide 40

Slide 40 text

$ npm run test

Slide 41

Slide 41 text

INFO [karma]: Karma v0.10.10 server started at http://localhost:9876/ INFO [launcher]: Starting browser Chrome INFO [Chrome 35.0.1916 (Mac OS X 10.10.0)]: Connected on socket 0GvlxTukdDRVPKHoJxdB Chrome 35.0.1916 (Mac OS X 10.10.0) controllers encountered a declaration exception FAILED ReferenceError: module is not defined at null. (/Users/dcramer/Development/pyconsg-tutorial-bootstrap/ tests/js/controllersSpec.js:4:14) at /Users/dcramer/Development/pyconsg-tutorial-bootstrap/tests/js/ controllersSpec.js:3:1 Chrome 35.0.1916 (Mac OS X 10.10.0): Executed 1 of 1 (1 FAILED) (0 secs / 0.012 Chrome 35.0.1916 (Mac OS X 10.10.0): Executed 1 of 1 (1 FAILED) ERROR (0.153 secs / 0.012 secs)

Slide 42

Slide 42 text

Basic JS Debugging Chrome Developer Tools

Slide 43

Slide 43 text

View > Developer > JavaScript Console

Slide 44

Slide 44 text

Error: [$injector:unpr] http://errors.angularjs.org/1.2.18/$injector/unpr? p0=NaNoobarProvider%20%3C-%20%24foobar at Error (native) at http://localhost:5000/static/vendor/angular/angular.min.js:6:450 at http://localhost:5000/static/vendor/angular/angular.min.js:36:145 at Object.c [as get] (http://localhost:5000/static/vendor/angular/ angular.min.js:34:236) at http://localhost:5000/static/vendor/angular/angular.min.js:36:213 at c (http://localhost:5000/static/vendor/angular/angular.min.js:34:236) at d (http://localhost:5000/static/vendor/angular/angular.min.js:34:453) at Object.instantiate (http://localhost:5000/static/vendor/angular/ angular.min.js:35:103) at http://localhost:5000/static/vendor/angular/angular.min.js:67:284 at link (http://localhost:5000/static/vendor/angular-route/angular- route.min.js:7:248)

Slide 45

Slide 45 text

WARNING: Errors will be obscure!

Slide 46

Slide 46 text

Let’s start building!

Slide 47

Slide 47 text

# create the database $ bin/create-db # load sample data $ bin/load-mocks # run the webserver $ bin/web

Slide 48

Slide 48 text

No content

Slide 49

Slide 49 text

The Post List

Slide 50

Slide 50 text

$ less blog/api/post_index.py from blog.api.base import Resource from blog.models import Post class PostIndexResource(Resource): def get(self): """ Return a list of posts. """ post_list = Post.query.order_by( Post.pub_date.desc() )[:10] results = [] for post in post_list: results.append({ 'id': post.id, 'title': post.title, 'body': post.body, 'pubDate': post.pub_date.isoformat(), }) return results

Slide 51

Slide 51 text

$ less tests/python/api/test_post_index.py import json from datetime import datetime from blog.config import db from blog.models import Post def test_list(client): post1 = Post( title='Hello world!', body='Lorem ipsum dolor sit amet, consectetur adipiscing elit.', pub_date=datetime(2013, 9, 19, 22, 15, 24), ) db.session.add(post1) post2 = Post( title='Hello world (again)!', body='Integer ullamcorper erat ac aliquam mollis.', pub_date=datetime(2013, 9, 20, 22, 15, 24), ) db.session.add(post2) db.session.commit() resp = client.get('/api/0/posts/') assert resp.status_code == 200 data = json.loads(resp.data.decode('utf-8')) assert len(data) == 2 assert data[0]['id'] == post2.id assert data[1]['id'] == post1.id

Slide 52

Slide 52 text

$ py.test tests/

Slide 53

Slide 53 text

$ vi static/js/controllers.js 'use strict'; angular.module('blog.controllers', []) .controller('PostListCtrl', function($scope, $http){ $http.get('/api/0/posts/') .success(function(data){ $scope.postList = data; }); });

Slide 54

Slide 54 text

A note on IE support

Slide 55

Slide 55 text

// The preferred longer-version of dependency declaration. controller(['$http', function($http) {}]); // The shorter version we're going to be using, which // does not work with Internet Explorer. controller(function($http) {});

Slide 56

Slide 56 text

$ vi static/partials/post-list.html

Slide 57

Slide 57 text

$ vi static/js/app.js 'use strict'; angular.module('blog', [ // add ngRoute dependency 'ngRoute', // add our controller dependency 'blog.controllers' ]).config(function($routeProvider) { $routeProvider .when('/', { templateUrl: 'post-list.html', controller: 'PostListCtrl' }); });

Slide 58

Slide 58 text

# we need ngRoute! $ node_modules/.bin/bower install "angular- route#1.2.17" --save

Slide 59

Slide 59 text

$ less bower.json { // ... "dependencies": { "angular": "~1.2.17", "bootstrap": "~3.1.1", "angular-route": "1.2.17" } }

Slide 60

Slide 60 text

$ ls static/vendor/angular-route README.md angular-route.js angular-route.min.js angular-route.min.js.map bower.json

Slide 61

Slide 61 text

$ less templates/index.html

Slide 62

Slide 62 text

No content

Slide 63

Slide 63 text

The Post Details

Slide 64

Slide 64 text

$ less blog/api/post_details.py from blog.api.base import Resource from blog.models import Post class PostDetailsResource(Resource): def get(self, post_id): """ Return information about a given post. """ post = Post.query.get(post_id) if post is None: return '', 404 return { 'id': post.id, 'title': post.title, 'body': post.body, 'pubDate': post.pub_date.isoformat(), }

Slide 65

Slide 65 text

$ vi tests/python/api/test_post_details.py import json from blog.config import db from blog.models import Post def test_valid_post_on_get(client): post = Post( title='Hello world!', body='Lorem ipsum dolor sit amet, consectetur adipiscing elit.', ) db.session.add(post) db.session.commit() resp = client.get('/api/0/posts/{0}/'.format(post.id)) assert resp.status_code == 200 assert resp.headers['Content-Type'] == 'application/json', resp.data assert json.loads(resp.data.decode('utf-8')) == { 'id': post.id, 'title': post.title, 'body': post.body, 'pubDate': post.pub_date.isoformat(), }

Slide 66

Slide 66 text

$ py.test tests/

Slide 67

Slide 67 text

$ vi static/js/controllers.js angular.module('blog.controllers', ['ngRoute']) .controller('PostListCtrl', function($scope, $http){ $http.get('/api/0/posts/') .success(function(data){ $scope.postList = data; }); }); .controller('PostDetailsCtrl', function($scope, $routeParams, $http){ $http.get('/api/0/posts/' + $routeParams.post_id + '/') .success(function(data){ $scope.post = data; }); });

Slide 68

Slide 68 text

$ vi static/partials/post-details.html

{{ post.title }}

{{ post.body }}

Slide 69

Slide 69 text

$ vi static/js/app.js $routeProvider .when('/', { templateUrl: 'post-list.html', controller: 'PostListCtrl' }) .when('/posts/:post_id', { templateUrl: 'post-details.html', controller: 'PostDetailsCtrl' });

Slide 70

Slide 70 text

No content

Slide 71

Slide 71 text

Let’s refactor a bit..

Slide 72

Slide 72 text

Using Resolvers Preload Dependencies

Slide 73

Slide 73 text

$ vi static/js/app.js .when('/', { templateUrl: 'post-list.html', controller: 'PostListCtrl', resolve: { postListResponse: function($http) { return $http.get('/api/0/posts/'); } } })

Slide 74

Slide 74 text

$ vi static/js/controllers.js angular.module('blog.controllers', []) .controller('PostListCtrl', function($scope, postListResponse){ $scope.postList = postListResponse.data; })

Slide 75

Slide 75 text

$ vi static/js/app.js .when('/posts/:post_id', { templateUrl: 'post-details.html', controller: 'PostDetailsCtrl', resolve: { postDetailsResponse: function($http, $route) { var postId = $route.current.params.post_id; return $http.get('/api/0/posts/' + postId + '/'); } } });

Slide 76

Slide 76 text

$ vi static/js/controllers.js angular.module('blog.controllers', []) .controller('PostListCtrl', function($scope, postListResponse){ $scope.postList = postListResponse.data; }) .controller('PostDetailsCtrl', function($scope, postDetailsResponse){ $scope.post = postDetailsResponse.data; });

Slide 77

Slide 77 text

Testing Controllers

Slide 78

Slide 78 text

$ vi tests/js/controllersSpec.js 'use strict'; describe('controllers', function(){ beforeEach(module('blog.controllers')); describe('PostListCtrl', function(){ it('should bind postList', function(){ // TODO }); }); });

Slide 79

Slide 79 text

# we need ngMock! $ node_modules/.bin/bower install "angular- mocks#1.2.17" --save

Slide 80

Slide 80 text

$ vi tests/js/controllersSpec.js it('should bind postList', inject(function($controller){ var samplePost = {id: 1, title: 'Test', body: 'Foo bar'}; var $scope = {}; var ctrl = $controller('PostListCtrl', { $scope: $scope, postListResponse: {data: [samplePost]} }); expect($scope.postList.length).toBe(1); expect($scope.postList[0].id).toBe(samplePost.id); }));

Slide 81

Slide 81 text

$ npm run test

Slide 82

Slide 82 text

$ vi tests/js/controllersSpec.js describe('PostDetailsCtrl', function(){ it('should bind post', inject(function($controller){ var samplePost = {id: 1, title: 'Test', body: 'Foo bar'}; var $scope = {}; var ctrl = $controller('PostDetailsCtrl', { $scope: $scope, postDetailsResponse: {data: samplePost} }); expect($scope.post.id).toBe(samplePost.id); })); });

Slide 83

Slide 83 text

$ npm run test

Slide 84

Slide 84 text

The Post Create

Slide 85

Slide 85 text

$ vi blog/api/post_index.py from flask.ext.restful.reqparse import RequestParser from blog.api.base import Resource from blog.config import db from blog.models import Post class PostIndexResource(Resource): def get(self): # ... def post(self): """ Create a new post. """ parser = RequestParser() parser.add_argument('title', required=True) parser.add_argument('body', required=True) args = parser.parse_args() post = Post( title=args.title, body=args.body, ) db.session.add(post) db.session.commit() return { 'id': post.id, 'title': post.title, 'body': post.body, 'pubDate': post.pub_date.isoformat(), }, 201

Slide 86

Slide 86 text

$ vi tests/python/api/test_post_index.py def test_list(client): # ... def test_create_with_valid_params(client): title = 'Foo' body = 'Bar' # valid params resp = client.post('/api/0/posts/', data={ 'title': title, 'body': body, }, follow_redirects=True) assert resp.status_code == 201 data = json.loads(resp.data.decode('utf-8')) assert data['title'] == title assert data['body'] == body

Slide 87

Slide 87 text

$ py.test tests/

Slide 88

Slide 88 text

$ vi static/js/controllers.js angular.module('blog.controllers', ['ngRoute']) .controller('PostListCtrl', function($scope, postListResponse){ $scope.postList = postListResponse.data; }); .controller('PostDetailsCtrl', function($scope, postDetailsResponse){ $scope.post = postDetailsResponse.data; }) .controller('NewPostCtrl', function($location, $scope, $http){ $scope.formData = {}; $scope.saveForm = function(){ $http.post('/api/0/posts/' $scope.formData) .success(function(data){ $location.path('/posts/' + data.id); }); }; });

Slide 89

Slide 89 text

$ vi tests/js/controllersSpec.js describe('NewPostCtrl', function(){ var $httpBackend, samplePost; beforeEach(inject(function($injector){ samplePost = {id: 1, title: 'Test', body: 'Foo bar'}; $httpBackend = $injector.get('$httpBackend'); $httpBackend.when('POST', '/api/0/posts/').respond(samplePost); })); it('should support saveForm', inject(function($controller){ // TODO })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); });

Slide 90

Slide 90 text

$ vi tests/js/controllersSpec.js it('should support saveForm', inject(function($controller){ var $scope = {formData: samplePost}; var ctrl = $controller('NewPostCtrl', { $scope: $scope }); $httpBackend.expectPOST('/api/0/posts/', $scope.formData) .respond(201, samplePost); $scope.saveForm(); $httpBackend.flush(); }));

Slide 91

Slide 91 text

$ npm run test

Slide 92

Slide 92 text

$ vi static/partials/new-post.html Publish

Slide 93

Slide 93 text

$ vi static/js/app.js $routeProvider .when('/', { // ... }) .when('/posts/:post_id', { // ... }) .when('/new/post', { templateUrl: 'new-post.html', controller: 'NewPostCtrl' });

Slide 94

Slide 94 text

No content

Slide 95

Slide 95 text

Directives DOM Manipulation in Angular

Slide 96

Slide 96 text

Slide 97

Slide 97 text

# element-based directives # do not work in Internet # Explorer

Slide 98

Slide 98 text

Slide 99

Slide 99 text

ng-app ng-view ng-show ng-hide ng-if ng-repeat ng-class ng-click ng-submit

Slide 100

Slide 100 text

Applying Markdown

Slide 101

Slide 101 text

$ vi static/partials/post-details.html

{{ post.title }}

Slide 102

Slide 102 text

$ node_modules/.bin/bower install "angular- sanitize#1.2.17" --save

Slide 103

Slide 103 text

$ node_modules/.bin/bower install showdown --save

Slide 104

Slide 104 text

$ less templates/index.html

Slide 105

Slide 105 text

$ vi static/js/directives.js angular.module('blog.directives.markdown', ['ngSanitize']). directive('markdown', function($sanitize) { var markdownConverter = new Showdown.converter(); return { restrict: 'A', link: function (scope, element, attrs) { scope.$watch(attrs.markdown, function(newVal) { var html = $sanitize(markdownConverter.makeHtml(newVal)); element.html(html); }); } }; });

Slide 106

Slide 106 text

$ vi static/js/app.js 'use strict'; angular.module('blog', [ 'ngRoute', 'blog.controllers', 'blog.directives.markdown' ]).config(function($routeProvider) { // ... });

Slide 107

Slide 107 text

$ less templates/index.html

Slide 108

Slide 108 text

The Publish Date

Slide 109

Slide 109 text

$ vi static/partials/post-list.html

Slide 110

Slide 110 text

$ vi static/js/directives.js 'use strict'; angular.module('blog.directives.timeSince', []) .directive('timeSince', function($timeout) { return function(scope, element, attrs) { var $element = angular.element(element), timeout_id; function updateValue(){ var value = scope.$eval(attrs.timeSince); if (value) { element.text(moment.utc(value).fromNow()); } else { element.text(''); } timeout_id = $timeout(updateValue, 1000); } element.bind('$destroy', function() { $timeout.cancel(timeout_id); }); updateValue(); }; });

Slide 111

Slide 111 text

$ node_modules/.bin/bower install moment -- save

Slide 112

Slide 112 text

$ less templates/index.html

Slide 113

Slide 113 text

$ vi static/js/app.js 'use strict'; angular.module('blog', [ 'ngRoute', 'blog.controllers', 'blog.directives.markdown' 'blog.directives.timeSince' ]).config(function($routeProvider) { // ... });

Slide 114

Slide 114 text

A word of caution! The $digest dilemma

Slide 115

Slide 115 text

Things that cause a digest: $timeout $watch $digest $scope.$apply filters (likely another 100 things)

Slide 116

Slide 116 text

Minimize the # of $digests!

Slide 117

Slide 117 text

$ vi static/js/directives.js .directive('timeSince', function($timeout) { return function(scope, element, attrs) { // ... function timeUntilTick(age) { if (age < 1) { return 1; } else if (age < 60) { return 30; } else if (age < 180) { return 300; } else { return 3600; } } function updateValue(){ // ... var age = moment().diff(moment.utc(value), 'minute'); timeout_id = $timeout(updateValue, timeUntilTick(age) * 1000); }

Slide 118

Slide 118 text

One step further would be a single shared $timeout

Slide 119

Slide 119 text

Refactoring the API Services in Angular

Slide 120

Slide 120 text

$ vi static/js/services.js angular.module('blog.services.api', []) .factory('api', function($http){ var api = {}, urlBase = '/api/0'; api.listPosts = function(){ return $http.get(urlBase + '/posts/'); }; api.createPost = function(data){ return $http.post(urlBase + '/posts/', data); }; api.getPost = function(id){ return $http.get(urlBase + '/posts/' + id + '/'); }; api.updatePost = function(id, data){ return $http.post(urlBase + '/posts/' + id + '/', data); }; return api; });

Slide 121

Slide 121 text

$ less templates/index.html

Slide 122

Slide 122 text

$ vi static/js/app.js 'use strict'; angular.module('blog', [ 'ngRoute', 'blog.controllers', 'blog.directives.timeSince', 'blog.services.api' ]).config(function($routeProvider) { // ... });

Slide 123

Slide 123 text

$ vi static/js/controllers.js angular.module('blog.controllers', ['ngRoute']) .controller('PostListCtrl', function($scope, postListResponse){ $scope.postList = postListResponse.data; }); .controller('PostDetailsCtrl', function($scope, postDetailsResponse){ $scope.post = postDetailsResponse.data; }) .controller('NewPostCtrl', function($location, $scope, api){ $scope.formData = {}; $scope.saveForm = function(){ api.createPost($scope.formData) .success(function(data){ $location.path('/posts/' + data.id); }); }; });

Slide 124

Slide 124 text

The Illusion of Realtime Long polling at it's best

Slide 125

Slide 125 text

$ vi static/js/controllers.js angular.module('blog.controllers', []) .controller('PostListCtrl', function($scope, $timeout, api, postListResponse){ var timeout_id; $scope.postList = postListResponse.data; $timeout(function(){ api.listPosts().success(function(data){ $scope.postList = data; }); }, 5000); $scope.$on('$destroy', function(){ $timeout.cancel(timeout_id); }); }) .controller('PostDetailsCtrl', function($scope, postDetailsResponse){ $scope.post = postDetailsResponse.data; });

Slide 126

Slide 126 text

A Loading Indicator An intro to $http interceptors

Slide 127

Slide 127 text

$ vi static/js/services.js angular.module('blog.services.loadingIndicator', []) .config(function($httpProvider){ var interceptor = function($q, $rootScope) { var reqsTotal = 0; var reqsCompleted = 0; return { request: function(config) { $rootScope.loading = true; reqsTotal++; return config; }, response: function(response) { reqsCompleted++; if (reqsCompleted >= reqsTotal) { $rootScope.loading = false; } return response; }, responseError: function(rejection) { reqsCompleted++; if (reqsCompleted >= reqsTotal) { $rootScope.loading = false; } return $q.reject(rejection); } }; }; $httpProvider.interceptors.push(interceptor); });

Slide 128

Slide 128 text

$ vi static/js/app.js 'use strict'; angular.module('blog', [ 'ngRoute', 'blog.controllers', 'blog.directives.timeSince', 'blog.services.api', 'blog.services.loadingIndicator' ]).config(function($routeProvider) { // ... });

Slide 129

Slide 129 text

$ vi templates/index.html

My Blog

Slide 130

Slide 130 text

A much more complex implementation: http://chieffancypants.github.io/angular- loading-bar/

Slide 131

Slide 131 text

Selenium Testing The Basics

Slide 132

Slide 132 text

$ vi tests/protractor.conf.js exports.config = { allScriptsTimeout: 11000, specs: [ 'e2e/*.js' ], capabilities: { 'browserName': 'chrome' }, baseUrl: 'http://localhost:5000/', framework: 'jasmine', jasmineNodeOpts: { defaultTimeoutInterval: 30000 } };

Slide 133

Slide 133 text

$ vi tests/e2e/scenarios.js 'use strict'; describe('blog', function() { browser.get('/'); describe('index', function() { beforeEach(function() { browser.get('/#/'); }); it('should render the post list', function() { expect(element.all(by.css('[ng-view] a')).first().getText()). toMatch(/Hello world \(again\)\!/); }); }); });

Slide 134

Slide 134 text

$ vi package.json { // ... "scripts": { "postinstall": "bower install", "pretest": "npm install", "test": "karma start tests/karma.conf.js", "preupdate-webdriver": "npm install", "update-webdriver": "webdriver-manager update", "preprotractor": "npm run update-webdriver", "protractor": "protractor tests/protractor.conf.js" } }

Slide 135

Slide 135 text

$ npm install protractor — save-dev

Slide 136

Slide 136 text

# we need the service running $ bin/web

Slide 137

Slide 137 text

$ npm run protractor

Slide 138

Slide 138 text

Looking Back Things to Remember

Slide 139

Slide 139 text

Scoped Context

Slide 140

Slide 140 text

Basic Dependency Injection

Slide 141

Slide 141 text

DOM via Directives

Slide 142

Slide 142 text

Digests are Expensive!

Slide 143

Slide 143 text

Building Modular Components using Modules/Services

Slide 144

Slide 144 text

$ git checkout finished

Slide 145

Slide 145 text

Additional Reading

Slide 146

Slide 146 text

https://github.com/dcramer/pyconsg- tutorial-example

Slide 147

Slide 147 text

https://github.com/angular-ui/ui-router

Slide 148

Slide 148 text

http://angular-ui.github.io/bootstrap/

Slide 149

Slide 149 text

https://github.com/witoldsz/angular-http- auth

Slide 150

Slide 150 text

http://requirejs.org/

Slide 151

Slide 151 text

https://github.com/dropbox/changes