AngularJS ()=> code with passion;

Tuesday, March 21, 2017

AngularJS is the leading Open Source JavaScript Application Framework backed by Google. The newest version Angular 2 && 4 or Just Angular is faster and production, cloud ready now.

Open Source Rules!

My selection of awesome future Open Source technologies (are you ready to party? harder, better, faster, stronger):




attitude, facts and mission ...

we are fearless, ruthless and honest, the goal is progress. we are constantly focused on our goal, produce quality working software as fast as possible. we are open source. we are the angular open source crisis team.

joy




hello world

<!doctype html> <html ng-app="myApp"> <head> <title>work hard, be kind, do more ...</title> </head> <body ng-controller="MyCtrl"> Say hello to: <input type="text" ng-model="name"> <h1>Good Morning {{getName()}}</h1> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script> <script> angular.module('myApp', []).controller('MyCtrl', ['$scope', function($scope) { $scope.name = 'World'; $scope.getName = () => { return $scope.name + ' !!!'; }; }]); </script> </body> </html>


ng-repeat

<!doctype html> <html ng-app="myApp"> <head> <title>work hard, be kind, do more ...</title> </head> <body ng-controller="MyCtrl"> <ul> <li ng-repeat="country in countries"> {{country.name}} has a population of {{country.population}}, {{worldsPercentage(country.population)}} % of world's population </li> <hr> World's population: {{population}} in millions </ul> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script> <script> angular.module('myApp', []).controller('MyCtrl', ['$scope', function($scope) { $scope.population = 7500; $scope.countries = [ { name: 'Germany', population: 80.6 }, { name: 'France', population: 63.1 }, { name: 'UK', population: 61.8} ]; $scope.worldsPercentage = (countryPopulation) => { return ((countryPopulation / $scope.population) * 100).toFixed(3); }; }]); </script> </body> </html>


simple form

<!doctype html> <html ng-app="myApp"> <head> <title>work hard, be kind, do more ...</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <style> .text-warning { background-color: red; color: white; } </style> </head> <body ng-controller="MyCtrl"> <div class="container"> <div class="row"> <span ng-class="{'text-warning' : shouldWarn()}">Remaining: {{remaining()}}</span> </div> <div class="row"> <textarea ng-model="message">{{message}}</textarea> </div> <div class="row"> <button class="btn btn-primary" ng-disabled="!hasValidLength()" ng-click="send()">Send</button> <button class="btn btn-warning" ng-click="clear()">Clear</button> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script> <script> angular.module('myApp', []).controller('MyCtrl', ['$scope', function($scope) { const MAX_LEN = 100; const WARN_THRESHOLD = 10; $scope.remaining = () => { return $scope.message ? MAX_LEN - $scope.message.length : 100; }; $scope.shouldWarn = () => { return $scope.remaining() < WARN_THRESHOLD; }; $scope.hasValidLength = () => { return $scope.message ? $scope.message.length > 0 : 0; }; $scope.send = () => { //do something with the data }; $scope.clear = () => { $scope.message = ''; }; }]); </script> </body> </html>


value recipe

<!doctype html> <html ng-app="myApp"> <head> <title>work hard, be kind, do more ...</title> </head> <body ng-controller="MyCtrl as ctrl"> Client ID: {{ctrl.clientId}} <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script> <script> angular.module('myApp', []).controller('MyCtrl', ['clientId', function(clientId) { this.clientId = clientId; }]) .value('clientId', 'a1234567890x'); </script> </body> </html>


factory recipe

<!doctype html> <html ng-app="myApp"> <head> <title>work hard, be kind, do more ...</title> </head> <body ng-controller="MyCtrl as ctrl"> API Token: {{ctrl.apiToken}} <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script> <script> angular.module('myApp', []).controller('MyCtrl', ['apiToken', function(apiToken) { this.apiToken = apiToken; }]) .value('clientId', 'a1234567890x') .factory('apiToken', ['clientId', function apiTokenFactory(clientId) { let encrypt = function(data1, data2) { return (data1 + ':' + data2).toUpperCase(); }; window.localStorage.setItem('myApp.secret', 'tellmeallyoursecrets'); let secret = window.localStorage.getItem('myApp.secret'); let apiToken = encrypt(clientId, secret); return apiToken; }]); </script> </body> </html>


service recipe

<!doctype html> <html ng-app="myApp"> <head> <title>work hard, be kind, do more ...</title> </head> <body ng-controller="MyCtrl as ctrl"> Unicorn Launcher: {{ctrl.uLaunch}} <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script> <script> angular.module('myApp', []).controller('MyCtrl', ['unicornLauncher', function(unicornLauncher) { this.uLaunch = unicornLauncher; }]) .value('clientId', 'a1234567890x') .factory('apiToken', ['clientId', function apiTokenFactory(clientId) { let encrypt = function(data1, data2) { return (data1 + ':' + data2).toUpperCase(); }; window.localStorage.setItem('myApp.secret', 'tellmeallyoursecrets'); let secret = window.localStorage.getItem('myApp.secret'); let apiToken = encrypt(clientId, secret); return apiToken; }]) .service('unicornLauncher', ['apiToken', UnicornLauncher]); function UnicornLauncher(apiToken) { this.launchedCount = 100; this.launch = function() { //make request to remote API, include token this.launchedCount++; } } </script> </body> </html>


provider recipe

<!doctype html> <html ng-app="myApp"> <head> <title>work hard, be kind, do more ...</title> </head> <body ng-controller="MyCtrl as ctrl"> Unicorn Launcher: {{ctrl.uLaunch}} <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script> <script> angular.module('myApp', []).controller('MyCtrl', ['unicornLauncher', function(unicornLauncher) { this.uLaunch = unicornLauncher; }]) .config(['unicornLauncherProvider', function (unicornLauncherProvider) { unicornLauncherProvider.useTinfoilShielding(true); }]) .value('clientId', 'a1234567890x') .factory('apiToken', ['clientId', function apiTokenFactory(clientId) { let encrypt = function(data1, data2) { return (data1 + ':' + data2).toUpperCase(); }; window.localStorage.setItem('myApp.secret', 'tellmeallyoursecrets'); let secret = window.localStorage.getItem('myApp.secret'); let apiToken = encrypt(clientId, secret); return apiToken; }]) .service('unicornLauncher', ['apiToken', UnicornLauncher]) .provider('unicornLauncher', function UnicornLauncherProvider() { let useTinfoilShielding = false; this.useTinfoilShielding = (value) => { useTinfoilShielding = !!value; }; this.$get = ['apiToken', function unicornLauncherFactory(apiToken) { return new UnicornLauncher(apiToken, useTinfoilShielding); }]; }); function UnicornLauncher(apiToken, useTinfoilShielding) { this.launchedCount = 100; this.launch = function() { //make request to remote API, include token this.launchedCount++; } } </script> </body> </html>


constant recipe

<!doctype html> <html ng-app="myApp"> <head> <title>work hard, be kind, do more ...</title> </head> <body ng-controller="MyCtrl as ctrl"> ClientId: {{ctrl.clientId}} <br> Planet Name: {{ctrl.planetName}} <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script> <script> angular.module('myApp', []).controller('MyCtrl', ['clientId', 'planetName', function(clientId, planetName) { this.clientId = clientId; this.planetName = planetName; }]) .value('clientId', 'a1234567890x') .constant('planetName', 'Mars'); </script> </body> </html>


writting a test spec: testing a controller

controller: 'use strict'; angular.module('myApp.view1', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/view1', { template: ` Enter password: <input type="password" ng-model="password"> <button ng-click="grade()">Grade</button> {{strength}} `, controller: 'PasswordCtrl' }); }]).controller('PasswordCtrl', ['$scope', function($scope) { $scope.password = ''; $scope.grade = () => { let size = $scope.password.length; if (size > 10) { $scope.strength = 'strong'; } else if (size > 3) { $scope.strength = 'medium'; } else { $scope.strength = 'weak'; } }; }]); test spec: 'use strict'; describe('myApp.view1 module', () => { beforeEach(module('myApp.view1')); describe('view1 PasswordCtrl', () => { let $controller; beforeEach(inject(function(_$controller_) { $controller = _$controller_; })); describe('$scope.grade', () => { it('should set strength to strong if password length is > 10 chars', () => { let $scope = {}; let ctrl = $controller('PasswordCtrl', {$scope: $scope}); $scope.password = 'longerthantenchars'; $scope.grade(); expect($scope.strength).toEqual('strong'); }); }); }); });


unit test for password weak

'use strict'; describe('myApp.view1 module', () => { beforeEach(module('myApp.view1')); describe('view1 PasswordCtrl', () => { let $controller; beforeEach(inject(function(_$controller_) { $controller = _$controller_; })); describe('$scope.grade', () => { let $scope, controller; beforeEach(() => { $scope = {}; controller = $controller('PasswordCtrl', {$scope: $scope}); }); it('should set strength to strong if password length is > 10 chars', () => { $scope.password = 'longerthantenchars'; $scope.grade(); expect($scope.strength).toEqual('strong'); }); it('should set strength to weak if password length < 3 chars', () => { $scope.password = 'x'; $scope.grade(); expect($scope.strength).toEqual('weak'); }); }); }); });


testing filters

filter: 'use strict'; angular.module('myApp.view1', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/view1', { template: ` Enter password: <input type="text" ng-model="password"> {{password | length}} `, controller: 'PasswordCtrl' }); }]).controller('PasswordCtrl', ['$scope', function($scope) { //$scope.password = 'abc.xyze2e012345678910'; }]).filter('length', function() { return (text) => { return ('' + (text || '')).length; } }); test spec: 'use strict'; describe('myApp.view1 module', () => { beforeEach(module('myApp.view1')); describe('length filter', () => { let $filter; beforeEach(inject(function(_$filter_) { $filter = _$filter_; })); it('returns 0 when given null', () => { let length = $filter('length'); expect(length(null)).toEqual(0); }); it('returns the correct value when given a string of chars', () => { let length = $filter('length'); expect(length('abc.xyze2e')).toEqual(10); }); }); });


testing directives

directive: 'use strict'; angular.module('myApp.view1', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/view1', { template: ` <a-great-eye></a-great-eye> `, controller: 'MyCtrl' }); }]).controller('MyCtrl', ['$scope', function($scope) { }]).directive('aGreatEye', function() { return { restrict: 'E', replace: true, template: '<h1>the will to win is nothing without the will to prepare, {{ 1 + 2 }} times.</h1>' }; }); test spec: 'use strict'; describe('myApp.view1 module', () => { //load myApp.view1 module which contains the directive beforeEach(module('myApp.view1')); describe('Unit testing great quotes', () => { let $compile, $rootScope; //store references to $rootScope and $compile //so they are available to all tests in the describe block beforeEach(inject(function(_$compile_, _$rootScope_) { //the injector wraps the underscores (_) from around the parameter names when matching $compile = _$compile_; $rootScope = _$rootScope_; })); it('replaces the element with the appropriate content', () => { //compile a piece of HTML containing the directive let element = $compile('<a-great-eye></a-great-eye>')($rootScope); //fire all the watches, so the scope expression {{ 1 + 2 }} will be evaluated $rootScope.$digest(); //check the compiled element contains the templated content expect(element.html()).toContain('the will to win is nothing without the will to prepare, 3 times.'); }); }); });


routing

<!doctype html> <html ng-app="myApp"> <head> <title>work hard, be kind, do more ...</title> </head> <body> Select: <br> <a href="#!/technologies">Technologies</a> <a href="#!/categories">Categories</a> <div ng-view></div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-route.min.js"></script> <script> angular.module('myApp', ['ngRoute']).config( function($routeProvider) { $routeProvider .when('/technologies', { template: 'Technologies: ReactJS, VueJS, AngularJS, BackboneJS, Just Angular, Polymer 2.0 ...' }) .when('/categories', { template: 'Single Page Applications, Front End Frameworks, Platforms, Web Components ...' }) .otherwise({ redirectTo: '/' }); }); </script> </body> </html>


factory and dependency injection

<!doctype html> <html ng-app="myApp"> <head> <title>work hard, be kind, do more ...</title> </head> <body ng-controller="MyCtrl"> <pre>{{technologyData}}</pre> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script> angular.module('myApp', []).controller('MyCtrl', ['$scope', 'technology', function($scope, technology) { $scope.technologyData = technology.getTechnologies(); }]) .factory('technology', function() { return { getTechnologies : () => { return 'ReactJS, VueJS, AngularJS, BackboneJS, Just Angular, Polymer 2.0 ...'; } } }); </script> </body> </html>


service and dependency injection

<!doctype html> <html ng-app="myApp"> <head> <title>work hard, be kind, do more ...</title> </head> <body ng-controller="MyCtrl"> <pre>{{technologyData}}</pre> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script> angular.module('myApp', []).controller('MyCtrl', ['$scope', 'technology', function($scope, technology) { $scope.technologyData = technology.getTechnologies(); }]) .service('technology', function() { this.getTechnologies = () => { return 'ReactJS, VueJS, AngularJS, BackboneJS, Just Angular, Polymer 2.0 ...'; }; }); </script> </body> </html>


component based architecture: component router and myapp component setup

<!doctype html> <html ng-app="myApp"> <head> <base href="/"> <title>work hard, be kind, do more ...</title> <link rel="stylesheet" href="assets/css/app.css"> </head> <body> <ng-outlet></ng-outlet> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script src="https://unpkg.com/@angular/router@0.2.0/angular1/angular_1_router.js"></script> <script> angular.module('myApp', ['ngComponentRouter']) .config(['$locationProvider', function($locationProvider) { $locationProvider.html5Mode(true); }]) .run(['$rootRouter', function($rootRouter) { $rootRouter.config([ {path: '/...', component: 'myApp'} ]); }]) .component('myApp', { $routeConfig: [ {path: '/', component: 'myDashboard', name: 'Dashboard'}, {path: '/villains', component: 'myVillains', name: 'EditVillains'} ], template: ` <img src="assets/images/villain.svg" class="logo"> <h1>Villainy<br>App</h1> <my-navigation-menu></my-navigation-menu> <ng-outlet></ng-outlet> ` }); </script> </body> </html>


component based architecture: mynavigationmenu component

<!doctype html> <html ng-app="myApp"> <head> <base href="/"> <title>work hard, be kind, do more ...</title> <link rel="stylesheet" href="assets/css/app.css"> </head> <body> <ng-outlet></ng-outlet> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script src="https://unpkg.com/@angular/router@0.2.0/angular1/angular_1_router.js"></script> <script> angular.module('myApp', ['ngComponentRouter', 'myNavigationMenuComponent']) .config(['$locationProvider', function($locationProvider) { $locationProvider.html5Mode(true); }]) .run(['$rootRouter', function($rootRouter) { $rootRouter.config([ {path: '/...', component: 'myApp'} ]); }]) .component('myApp', { $routeConfig: [ {path: '/', component: 'myDashboard', name: 'Dashboard'}, {path: '/villains', component: 'myVillains', name: 'EditVillains'} ], template: ` <img src="assets/images/villain.svg" class="logo"> <h1>Villainy<br>App</h1> <my-navigation-menu></my-navigation-menu> <ng-outlet></ng-outlet> ` }); angular.module('myNavigationMenuComponent', ['ngComponentRouter']) .component('myNavigationMenu', { template: ` <nav> <a ng-link="['Dashboard']">Dashboard</a> <a ng-link="['EditVillains']">Edit Villains</a> </nav> ` }); </script> </body> </html>


component based architecture: mydashboard && myfavoritevillains component

<!doctype html> <html ng-app="myApp"> <head> <base href="/"> <title>work hard, be kind, do more ...</title> <link rel="stylesheet" href="assets/css/app.css"> </head> <body> <ng-outlet></ng-outlet> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script src="https://unpkg.com/@angular/router@0.2.0/angular1/angular_1_router.js"></script> <script> angular.module('myApp', ['ngComponentRouter', 'myNavigationMenuComponent', 'myDashboardComponent']) .config(['$locationProvider', function($locationProvider) { $locationProvider.html5Mode(true); }]) .run(['$rootRouter', function($rootRouter) { $rootRouter.config([ {path: '/...', component: 'myApp'} ]); }]) .component('myApp', { $routeConfig: [ {path: '/', component: 'myDashboard', name: 'Dashboard'}, {path: '/villains', component: 'myVillains', name: 'EditVillains'} ], template: ` <img src="assets/images/villain.svg" class="logo"> <h1>Villainy<br>App</h1> <my-navigation-menu></my-navigation-menu> <ng-outlet></ng-outlet> ` }); angular.module('myNavigationMenuComponent', ['ngComponentRouter']) .component('myNavigationMenu', { template: ` <nav> <a ng-link="['Dashboard']">Dashboard</a> <a ng-link="['EditVillains']">Edit Villains</a> </nav> ` }); angular.module('myDashboardComponent', ['myFavoriteVillainsComponent']) .component('myDashboard', { template: ` <div> <p>Welcome to the Villains App</p> <my-favorite-villains></my-favorite-villains> </div> ` }); angular.module('myFavoriteVillainsComponent', []) .component('myFavoriteVillains', { template: ` <div> <h2>Favorites</h2> <ul class="favorites"> <li>Bill <strong>'The Butcher' Cutting</strong></li> <li>Pennywise <strong>The Dancing Clown</strong></li> <li>Agent <strong>Smith</strong></li> <li>Joker <strong>...</strong></li> </ul> </div> ` }); </script> </body> </html>


component based architecture: myfavoritevillains component remastered and villainsservice service implementation

<!doctype html> <html ng-app="myApp"> <head> <base href="/"> <title>work hard, be kind, do more ...</title> <link rel="stylesheet" href="assets/css/app.css"> </head> <body> <ng-outlet></ng-outlet> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script src="https://unpkg.com/@angular/router@0.2.0/angular1/angular_1_router.js"></script> <script> angular.module('myApp', ['ngComponentRouter', 'myNavigationMenuComponent', 'myDashboardComponent', 'villains']) .config(['$locationProvider', function($locationProvider) { $locationProvider.html5Mode(true); }]) .run(['$rootRouter', function($rootRouter) { $rootRouter.config([ {path: '/...', component: 'myApp'} ]); }]) .component('myApp', { $routeConfig: [ {path: '/', component: 'myDashboard', name: 'Dashboard'}, {path: '/villains', component: 'myVillains', name: 'EditVillains'} ], template: ` <img src="assets/images/villain.svg" class="logo"> <h1>Villainy<br>App</h1> <my-navigation-menu></my-navigation-menu> <ng-outlet></ng-outlet> ` }); angular.module('myNavigationMenuComponent', ['ngComponentRouter']) .component('myNavigationMenu', { template: ` <nav> <a ng-link="['Dashboard']">Dashboard</a> <a ng-link="['EditVillains']">Edit Villains</a> </nav> ` }); angular.module('myDashboardComponent', ['myFavoriteVillainsComponent']) .component('myDashboard', { template: ` <div> <p>Welcome to the Villains App</p> <my-favorite-villains></my-favorite-villains> </div> ` }); angular.module('villains', ['myFavoriteVillainsComponent', 'VillainsService']); angular.module('myFavoriteVillainsComponent', ['VillainsService']) .component('myFavoriteVillains', { template: ` <div> <h2>Favorites</h2> <ul class="favorites"> <li ng-repeat="villain in $ctrl.villains | filter: $ctrl.isFavorite"> {{villain.firstName}} <strong>{{villain.lastName}}</strong></li> </ul> </div> `, controller: function MyFavoriteVillains(villainsService) { this.$onInit = function() { villainsService.getVillains().then((villains) => { this.villains = villains; }); }; this.isFavorite = (villain) => { return villainsService.isFavorite(villain); }; } }); angular.module('VillainsService', []).factory('villainsService', ['$q', function($q) { const VILLAINS = [ {id: 0, firstName: 'Bill', lastName: "'The Butcher' Cutting" }, {id: 1, firstName: 'Pennywise', lastName: 'The Dancing Clown' }, {id: 2, firstName: 'Agent' , lastName: 'Smith'}, {id: 3, firstName: 'Joker', lastName: '...'} ]; let favorites = { 0: true, 2: true }; return { getVillains : () => { return $q.when(VILLAINS); }, save: (id, firstName, lastName) => { //find villain and replace it with new data let index= 0; while(index < VILLAINS.length && VILLAINS[index].id !== id) { index += 1; } VILLAINS.splice(index, 1, { id: id, firstName: firstName, lastName: lastName}); }, toggleFavorite: (villain) => { favorites[villain.id] = !favorites[villain.id]; }, isFavorite: (villain) => { return favorites[villain.id]; } }; }]); </script> </body> </html>


component based architecture: myvillainscomponent component

<!doctype html> <html ng-app="myApp"> <head> <base href="/"> <title>work hard, be kind, do more ...</title> <link rel="stylesheet" href="assets/css/app.css"> </head> <body> <ng-outlet></ng-outlet> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script src="https://unpkg.com/@angular/router@0.2.0/angular1/angular_1_router.js"></script> <script> angular.module('myApp', ['ngComponentRouter', 'myNavigationMenuComponent', 'myDashboardComponent', 'villains']) .config(['$locationProvider', function($locationProvider) { $locationProvider.html5Mode(true); }]) .run(['$rootRouter', function($rootRouter) { $rootRouter.config([ {path: '/...', component: 'myApp'} ]); }]) .component('myApp', { $routeConfig: [ {path: '/', component: 'myDashboard', name: 'Dashboard'}, {path: '/villains', component: 'myVillains', name: 'EditVillains'} ], template: ` <img src="assets/images/villain.svg" class="logo"> <h1>Villainy<br>App</h1> <my-navigation-menu></my-navigation-menu> <ng-outlet></ng-outlet> ` }); angular.module('myNavigationMenuComponent', ['ngComponentRouter']) .component('myNavigationMenu', { template: ` <nav> <a ng-link="['Dashboard']">Dashboard</a> <a ng-link="['EditVillains']">Edit Villains</a> </nav> ` }); angular.module('myDashboardComponent', ['myFavoriteVillainsComponent']) .component('myDashboard', { template: ` <div> <p>Welcome to the Villains App</p> <my-favorite-villains></my-favorite-villains> </div> ` }); angular.module('villains', ['myFavoriteVillainsComponent', 'myVillainsComponent', 'VillainsService']); angular.module('myFavoriteVillainsComponent', ['VillainsService']) .component('myFavoriteVillains', { template: ` <div> <h2>Favorites</h2> <ul class="favorites"> <li ng-repeat="villain in $ctrl.villains | filter: $ctrl.isFavorite"> {{villain.firstName}} <strong>{{villain.lastName}}</strong></li> </ul> </div> `, controller: function MyFavoriteVillains(villainsService) { this.$onInit = function() { villainsService.getVillains().then((villains) => { this.villains = villains; }); }; this.isFavorite = (villain) => { return villainsService.isFavorite(villain); }; } }); angular.module('myVillainsComponent', ['myFavoriteVillainsComponent', 'VillainsService']) .component('myVillains', { template: ` <div class="my-villains"> <div class="edit-list"> <h2>Edit Villains</h2> <div ng-repeat="villain in $ctrl.villains track by villain.id"> <my-villain villain="villain" is-favorite="$ctrl.isFavorite(villain)" on-villain-change="$ctrl.saveVillain(villain, $event.firstName, $event.lastName)" on-is-favorite-change="$ctrl.toggleFavorite(villain)"> </my-villain> </div> <p> Click on a villains name to change it.<br> Changes are saved when you press enter or leave the edit box.<br> Cancel changes by pressing escape.<br> </p> </div> <my-favorite-villains></my-favorite-villains> </div> `, controller: MyVillains }); function MyVillains(villainsService) { this.villainsService = villainsService; } MyVillains.prototype = { $onInit: function() { this.loadVillains(); }, loadVillains: function() { const self = this; this.villainsService.getVillains().then((villains) => { this.villains = villains; }); }, saveVillain: function (villain, firstName, lastName) { this.villainsService.save(villain.id, firstName, lastName); }, toggleFavorite: function (villain) { this.villainsService.toggleFavorite(villain); }, isFavorite: function (villain) { return this.villainsService.isFavorite(villain); } }; angular.module('VillainsService', []).factory('villainsService', ['$q', function($q) { const VILLAINS = [ {id: 0, firstName: 'Bill', lastName: "'The Butcher' Cutting" }, {id: 1, firstName: 'Pennywise', lastName: 'The Dancing Clown' }, {id: 2, firstName: 'Agent' , lastName: 'Smith'}, {id: 3, firstName: 'Joker', lastName: '...'} ]; let favorites = { 0: true, 2: true }; return { getVillains : () => { return $q.when(VILLAINS); }, save: (id, firstName, lastName) => { //find villain and replace it with new data let index= 0; while(index < VILLAINS.length && VILLAINS[index].id !== id) { index += 1; } VILLAINS.splice(index, 1, { id: id, firstName: firstName, lastName: lastName}); }, toggleFavorite: (villain) => { favorites[villain.id] = !favorites[villain.id]; }, isFavorite: (villain) => { return favorites[villain.id]; } }; }]); </script> </body> </html>


component based architecture: myvillaincomponent component && mytakedirective directive implementation

<!doctype html> <html ng-app="myApp"> <head> <base href="/"> <title>work hard, be kind, do more ...</title> <link rel="stylesheet" href="assets/css/app.css"> </head> <body> <ng-outlet></ng-outlet> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script src="https://unpkg.com/@angular/router@0.2.0/angular1/angular_1_router.js"></script> <script> angular.module('myApp', ['ngComponentRouter', 'myNavigationMenuComponent', 'myDashboardComponent', 'villains']) .config(['$locationProvider', function($locationProvider) { $locationProvider.html5Mode(true); }]) .run(['$rootRouter', function($rootRouter) { $rootRouter.config([ {path: '/...', component: 'myApp'} ]); }]) .component('myApp', { $routeConfig: [ {path: '/', component: 'myDashboard', name: 'Dashboard'}, {path: '/villains', component: 'myVillains', name: 'EditVillains'} ], template: ` <img src="assets/images/villain.svg" class="logo"> <h1>Villainy<br>App</h1> <my-navigation-menu></my-navigation-menu> <ng-outlet></ng-outlet> ` }); angular.module('myNavigationMenuComponent', ['ngComponentRouter']) .component('myNavigationMenu', { template: ` <nav> <a ng-link="['Dashboard']">Dashboard</a> <a ng-link="['EditVillains']">Edit Villains</a> </nav> ` }); angular.module('myDashboardComponent', ['myFavoriteVillainsComponent']) .component('myDashboard', { template: ` <div> <p>Welcome to the Villains App</p> <my-favorite-villains></my-favorite-villains> </div> ` }); angular.module('villains', ['myFavoriteVillainsComponent', 'myVillainsComponent', 'myVillainComponent', 'VillainsService']); angular.module('myFavoriteVillainsComponent', ['VillainsService']) .component('myFavoriteVillains', { template: ` <div> <h2>Favorites</h2> <ul class="favorites"> <li ng-repeat="villain in $ctrl.villains | filter: $ctrl.isFavorite"> {{villain.firstName}} <strong>{{villain.lastName}}</strong></li> </ul> </div> `, controller: function MyFavoriteVillains(villainsService) { this.$onInit = function() { villainsService.getVillains().then((villains) => { this.villains = villains; }); }; this.isFavorite = (villain) => { return villainsService.isFavorite(villain); }; } }); angular.module('myVillainComponent', ['myTakeFocusDirective']) .component('myVillain', { template: ` <div class="my-villain"> <span class="full-name" ng-if="!$ctrl.editing" ng-click="$ctrl.editing=true"> {{$ctrl.fullName}} </span> <input class="full-name" type="text" my-take-focus="$ctrl.editing" ng-if="$ctrl.editing" ng-model="$ctrl.fullName" ng-blur="$ctrl.nameChanged()" ng-keyup="$ctrl.handleKey($event)"> &nbsp;&nbsp; <label>Like: <input type="checkbox" ng-model="$ctrl.isFavorite" ng-click="$ctrl.onIsFavoriteChange()"> </label> </div> `, bindings: { villain: '<', onVillainChange: '&', isFavorite: '<', onIsFavoriteChange: '&' }, controller: MyVillain }); function MyVillain() {} MyVillain.prototype = { $onChanges: function(changes) { if (changes.villain) { this.fullName = getFullName(changes.villain.currentValue); } }, nameChanged: function() { this.editing = false; this.onVillainChange({$event: splitName(this.fullName)}); }, handleKey: function($event) { switch($event.keyCode) { case 27: //ESC this.fullName = getFullName(this.villain); this.editing = false; $event.preventDefault(); break; case 13: //ENTER this.nameChanged(); $event.preventDefault(); break; } } }; function splitName(name) { let match = /(\w+)\s*(.*)/.exec(name); return { firstName: match[1], lastName: match[2] }; } function getFullName(villain) { return [villain.firstName, villain.lastName].join(' ').trim(); } angular.module('myTakeFocusDirective', []) .directive('myTakeFocus', function() { return function link(scope, element, attr){ scope.$watch(attr.myTakeFocus, (value) => { if (value) { element[0].focus(); } }); }; }); angular.module('myVillainsComponent', ['myFavoriteVillainsComponent', 'VillainsService']) .component('myVillains', { template: ` <div class="my-villains"> <div class="edit-list"> <h2>Edit Villains</h2> <div ng-repeat="villain in $ctrl.villains track by villain.id"> <my-villain villain="villain" is-favorite="$ctrl.isFavorite(villain)" on-villain-change="$ctrl.saveVillain(villain, $event.firstName, $event.lastName)" on-is-favorite-change="$ctrl.toggleFavorite(villain)"> </my-villain> </div> <p> Click on a villains name to change it.<br> Changes are saved when you press enter or leave the edit box.<br> Cancel changes by pressing escape.<br> </p> </div> <my-favorite-villains></my-favorite-villains> </div> `, controller: MyVillains }); function MyVillains(villainsService) { this.villainsService = villainsService; } MyVillains.prototype = { $onInit: function() { this.loadVillains(); }, loadVillains: function() { const self = this; this.villainsService.getVillains().then((villains) => { this.villains = villains; }); }, saveVillain: function (villain, firstName, lastName) { this.villainsService.save(villain.id, firstName, lastName); }, toggleFavorite: function (villain) { this.villainsService.toggleFavorite(villain); }, isFavorite: function (villain) { return this.villainsService.isFavorite(villain); } }; angular.module('VillainsService', []).factory('villainsService', ['$q', function($q) { const VILLAINS = [ {id: 0, firstName: 'Bill', lastName: "'The Butcher' Cutting" }, {id: 1, firstName: 'Pennywise', lastName: 'The Dancing Clown' }, {id: 2, firstName: 'Agent' , lastName: 'Smith'}, {id: 3, firstName: 'Joker', lastName: '...'} ]; let favorites = { 0: true, 2: true }; return { getVillains : () => { return $q.when(VILLAINS); }, save: (id, firstName, lastName) => { //find villain and replace it with new data let index= 0; while(index < VILLAINS.length && VILLAINS[index].id !== id) { index += 1; } VILLAINS.splice(index, 1, { id: id, firstName: firstName, lastName: lastName}); }, toggleFavorite: (villain) => { favorites[villain.id] = !favorites[villain.id]; }, isFavorite: (villain) => { return favorites[villain.id]; } }; }]); </script> </body> </html>


firebase && angularfire: 3 way object bindings

<!doctype html> <html ng-app="myApp"> <head> <title>angularfire the fire of desire ...</title> </head> <body ng-controller="FireCtrl"> <!--everything typed here is immediately saved in our firebase database --> <input type="text" ng-model="data.text"> <!-- all changes from our firebase database appear here in real time --> <h1>You said: {{data.text}}</h1> <!-- AngularJS --> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <!-- Firebase --> <script src="https://www.gstatic.com/firebasejs/3.7.2/firebase.js"></script> <!-- AngularFire --> <script src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js"></script> <script> // Initialize Firebase SDK var config = { apiKey: "AIzaSyBN1zVUFMKTH90DYuSfkJSi4N1HTpoZrWI", authDomain: "ng2-investigator.firebaseapp.com", databaseURL: "https://ng2-investigator.firebaseio.com", storageBucket: "ng2-investigator.appspot.com", messagingSenderId: "112006120191" }; firebase.initializeApp(config); </script> <script> angular.module('myApp', ['firebase']) .controller('FireCtrl', ['$scope', '$firebaseObject', function($scope, $firebaseObject){ const ref = firebase.database().ref().child('data'); //download data into local object let syncObject = $firebaseObject(ref); //synchronize object with 3 way data binding syncObject.$bindTo($scope, 'data'); }]); </script> </body> </html>


firebase && angularfire: synchronize collections as arrays

<!doctype html> <html ng-app="myApp"> <head> <title>angularfire the fire of desire ...</title> </head> <body ng-controller="FireCtrl"> <ul> <li ng-repeat="message in messages"> <!-- edit a message --> <input ng-model="message.text" ng-change="messages.$save(message)"> <!-- delete a message --> <button ng-click="messages.$remove(message)">Delete Message</button> </li> </ul> <!-- push a new message into the array --> <form ng-submit="addMessage()"> <input ng-model="newMessageText"> <button type="submit">Add Message</button> </form> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script src="https://www.gstatic.com/firebasejs/3.7.2/firebase.js"></script> <script src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js"></script> <script> var config = { apiKey: "AIzaSyBN1zVUFMKTH90DYuSfkJSi4N1HTpoZrWI", authDomain: "ng2-investigator.firebaseapp.com", databaseURL: "https://ng2-investigator.firebaseio.com", storageBucket: "ng2-investigator.appspot.com", messagingSenderId: "112006120191" }; firebase.initializeApp(config); </script> <script> angular.module('myApp', ['firebase']) .controller('FireCtrl', ['$scope', '$firebaseArray', function($scope, $firebaseArray){ const ref = firebase.database().ref().child('messages'); //create a synchronized array $scope.messages = $firebaseArray(ref); //add new items to array //message is automatically added to our firebase database $scope.addMessage = () => { $scope.messages.$add({text: $scope.newMessageText}); $scope.newMessageText = ''; }; }]); </script> </body> </html>


firebase && angularfire: simple chat room

<!doctype html> <html ng-app="myApp"> <head> <title>angularfire the fire of desire ...</title> </head> <body ng-controller="ChatCtrl"> <ul> <li ng-repeat="message in messages"> {{message.from}}: {{message.content}} </li> </ul> <form ng-submit="addMessage()"> <input type="text" ng-model="message"> <input type="submit" value="Add Message"> </form> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script src="https://www.gstatic.com/firebasejs/3.7.2/firebase.js"></script> <script src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js"></script> <script> var config = { apiKey: "AIzaSyBN1zVUFMKTH90DYuSfkJSi4N1HTpoZrWI", authDomain: "ng2-investigator.firebaseapp.com", databaseURL: "https://ng2-investigator.firebaseio.com", storageBucket: "ng2-investigator.appspot.com", messagingSenderId: "112006120191" }; firebase.initializeApp(config); </script> <script> angular.module('myApp', ['firebase']) .factory('chatMessages', ['$firebaseArray', function($firebaseArray) { //const ref = firebase.database().ref().child('messages'); //create reference to database location where we will store our data const ref = firebase.database().ref().child('chatmessages'); //this uses angularfire to create the synchronized array return $firebaseArray(ref); }]) .controller('ChatCtrl', ['$scope', 'chatMessages', function($scope, chatMessages){ $scope.user = 'Guest ' + Math.round(Math.random() * 100); //we add chatMessages to our scope to be used in our ng-repeat $scope.messages = chatMessages; //a method to create new messages; called by ng-submit $scope.addMessage = () => { //calling $add on a synchronized array is like Array.push(), //except that it saves changes to our database $scope.messages.$add({ from: $scope.user, content: $scope.message }); //reset message input $scope.message = ''; }; //if messages are empty, add something for fun! $scope.messages.$loaded(() => { if ($scope.messages.length === 0) { $scope.messages.$add({ from: 'Firebase Docs', content: 'we will destroy azure.' }); } }); }]); </script> </body> </html>


angular material: hello world

<!doctype html> <html ng-app="myApp"> <head> <title>angular material: beauty in life</title> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" /> <!-- Angular Material style sheet --> <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css"> <link rel='stylesheet' href='http://fonts.googleapis.com/css?family=Roboto:400,700'> </head> <body ng-cloak layout="column"> <!-- Container #1 --> <md-toolbar layout="row" class="md-toolbar-tools"> <h1>Welcome to Angular Material</h1> </md-toolbar> <!-- Container #2 --> <div flex layout="row"> <!-- Container #3 --> <md-sidenav md-is-locked-open="true" class=" md-padding md-whiteframe-4dp"> Sidenav </md-sidenav> <!-- Container #4 --> <md-content class="md-padding" flex id="content"> Content </md-content> </div> <!-- Angular Material requires Angular.js Libraries --> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script> <!-- Angular Material Library --> <script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script> <script> angular.module('myApp', ['ngMaterial']); </script> </body> </html>


angular material: autocomplete

<!doctype html> <html ng-app="myApp"> <head> <title>angular material: beauty in life</title> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" /> <!-- Angular Material style sheet --> <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css"> <link rel='stylesheet' href='http://fonts.googleapis.com/css?family=Roboto:400,700'> </head> <body ng-cloak layout="column" ng-controller="MyCtrl as ctrl"> <!-- Container #1 --> <md-toolbar layout="row" class="md-toolbar-tools"> <h1>Welcome to Angular Material</h1> </md-toolbar> <!-- Container #2 --> <div flex layout="row"> <!-- Container #3 --> <md-sidenav md-is-locked-open="true" class=" md-padding md-whiteframe-4dp"> My Technologies </md-sidenav> <!-- Container #4 --> <md-content class="md-padding" flex id="content"> <form ng-submit="$event.preventDefault()"> <md-autocomplete ng-disabled="ctrl.isDisabled" md-no-cache="ctrl.noCache" md-selected-item="ctrl.selectedItem" md-search-text-change="ctrl.searchTextChange(ctrl.searchText)" md-search-text="ctrl.searchText" md-selected-item-change="ctrl.selectedItemChange(item)" md-items="item in ctrl.querySearch(ctrl.searchText)" md-item-text="item.display" md-min-length="0" placeholder="What is your favorite JavaScript Framework?"> <md-item-template> <span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.display}}</span> </md-item-template> <md-not-found> No JavaScript Framework matching "{{ctrl.searchText}}" were found. <a ng-click="ctrl.newJavaScriptFramework(ctrl.searchText)">Create a new one!</a> </md-not-found> </md-autocomplete> </form> </md-content> </div> <!-- Angular Material requires Angular.js Libraries --> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script> <!-- Angular Material Library --> <script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script> <script> angular.module('myApp', ['ngMaterial']).controller('MyCtrl', MyCtrl); function MyCtrl ($log) { const self = this; self.isDisabled = false; self.technologies = loadTechnologies(); self.querySearch = querySearch; self.selectedItemChange = selectedItemChange; self.searchTextChange = searchTextChange; self.newJavaScriptFramework = newTechnology; function newTechnology(technology) { alert(`you'll need to create a new Technology for "${technology}"!`); } function querySearch (query) { let results = query ? self.technologies.filter( createFilterFor(query) ) : self.technologies, deferred; return results; } function searchTextChange(text) { $log.info('text changed to ' + text); } function selectedItemChange(item) { $log.info('item changed to ' + JSON.stringify(item)); } function loadTechnologies() { const allTechnologies = `AngularJS, Just Angular, BackboneJS, EmberJS, MeteorJS, Polymer, ReactJS, VueJS`; return allTechnologies.split(/, +/g).map((technology) => { return { value: technology.toLowerCase(), display: technology }; }); } function createFilterFor(query) { let lowercaseQuery = angular.lowercase(query); return function filterFn(technology) { return (technology.value.indexOf(lowercaseQuery) === 0); }; } } </script> </body> </html>


angular material: autocomplete in modal dialog

<!doctype html> <html ng-app="myApp"> <head> <title>angular material: beauty in life</title> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" /> <!-- Angular Material style sheet --> <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> </head> <body ng-cloak layout="column" ng-controller="MyCtrl as ctrl"> <!-- Container #1 --> <md-toolbar layout="row" class="md-toolbar-tools"> <h1>Welcome to Angular Material</h1> </md-toolbar> <!-- Container #2 --> <div flex layout="row"> <!-- Container #3 --> <md-sidenav md-is-locked-open="true" class=" md-padding md-whiteframe-4dp"> My Technologies </md-sidenav> <!-- Container #4 --> <md-content class="md-padding" flex id="content"> <md-button ng-click="ctrl.openDialog($event)" class="md-raised md-warn">Open Dialog</md-button> </md-content> </div> <!-- Angular Material requires Angular.js Libraries --> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script> <!-- Angular Material Library --> <script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script> <script> angular.module('myApp', ['ngMaterial']).controller('MyCtrl', MyCtrl); function MyCtrl($mdDialog) { const self = this; self.openDialog = ($event) => { $mdDialog.show({ controller: DialogCtrl, controllerAs: 'ctrl', template: ` <md-dialog aria-label="autocomplete dialog example"> <md-toolbar> <div class="md-toolbar-tools"> <h2>Autocomplete Dialog Example</h2> <span flex></span> <md-button class="md-icon-button" ng-click="ctrl.cancel()"> </md-button> </div> </md-toolbar> <md-dialog-content ng-cloak> <div class="md-dialog-content"> <form ng-submit="$event.preventDefault()"> <p>use <code>md-autocomplete</code> to search for matches from local or remote data sources. </p> <md-autocomplete md-selected-item="ctrl.selectedItem" md-search-text="ctrl.searchText" md-items="item in ctrl.querySearch(ctrl.searchText)" md-item-text="item.display" md-min-length="0" placeholder="what is your favorite JavaScript Framework?" md-autofocus> <md-item-template> <span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.display}}</span> </md-item-template> <md-not-found> No technologies matching "{{ctrl.searchText}}" were found. </md-not-found> </md-autocomplete> </form> </div> </md-dialog-content> <md-dialog-actions> <md-button aria-label="finished" ng-click="ctrl.finish($event)">Finished</md-button> </md-dialog-actions> </md-dialog> `, parent: angular.element(document.body), targetEvent: $event, clickOutsidetoClose: true }) } } function DialogCtrl ($mdDialog) { const self = this; self.technologies = loadTechnologies(); self.querySearch = querySearch; self.cancel = ($event) => { $mdDialog.cancel(); }; self.finish = ($event) => { $mdDialog.hide(); }; function querySearch (query) { return query ? self.technologies.filter( createFilterFor(query) ) : self.technologies; } function loadTechnologies() { const allTechnologies = `AngularJS, Just Angular, BackboneJS, EmberJS, MeteorJS, Polymer, ReactJS, VueJS`; return allTechnologies.split(/, +/g).map((technology) => { return { value: technology.toLowerCase(), display: technology }; }); } function createFilterFor(query) { let lowercaseQuery = angular.lowercase(query); return function filterFn(technology) { return (technology.value.indexOf(lowercaseQuery) === 0); }; } } </script> </body> </html>


angular material: buttons

<!doctype html> <html ng-app="myApp"> <head> <title>angular material: beauty in life</title> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" /> <!-- Angular Material style sheet --> <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> </head> <body ng-cloak layout="column"> <!-- Container #1 --> <md-toolbar layout="row" class="md-toolbar-tools"> <h1>Welcome to Angular Material</h1> </md-toolbar> <!-- Container #2 --> <div flex layout="row"> <!-- Container #3 --> <md-sidenav md-is-locked-open="true" class=" md-padding md-whiteframe-4dp"> My Technologies </md-sidenav> <!-- Container #4 --> <md-content class="md-padding" flex id="content"> <label>Raised</label> <section layout="row" layout-sm="column" layout-align="center center" layout-wrap> <md-button class="md-raised">Button</md-button> <md-button class="md-raised md-primary">Primary</md-button> <md-button ng-disabled="true" class="md-raised md-primary">Disabled</md-button> <md-button class="md-raised md-warn">Warn</md-button> </section> <label>FAB</label> <section layout="row" layout-sm="column" layout-align="center center" layout-wrap> <md-button class="md-fab md-primary md-hue-1" aria-label="android"> <i class="material-icons">android</i> </md-button> <md-button class="md-fab md-accent md-hue-2" aria-label="favorite"> <i class="material-icons">favorite</i> </md-button> <md-button class="md-fab md-accent md-raised md-hue-3" aria-label="flight takeoff"> <i class="material-icons">flight_takeoff</i> </md-button> <md-button class="md-fab md-primary md-mini" aria-label="grade"> <i class="material-icons">grade</i> </md-button> </section> <label>Themed</label> <section layout="row" layout-sm="column" layout-align="center center" layout-wrap> <md-button class="md-primary md-hue-1">Primary Hue 1</md-button> <md-button class="md-raised md-hue-2 md-warn">Warn Hue 2</md-button> <md-button class="md-accent">Accent</md-button> <md-button class="md-accent md-raised md-hue-1">Accent Hue 1</md-button> </section> </md-content> </div> <!-- Angular Material requires Angular.js Libraries --> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script> <!-- Angular Material Library --> <script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script> <script> angular.module('myApp', ['ngMaterial']); </script> </body> </html>


todo app

<!doctype html> <html ng-app="myApp"> <head> <title>work hard, be kind, do more</title> <style> .done-true { text-decoration: line-through; color: grey; } </style> </head> <body> <h2>Todos</h2> <div ng-controller="TodoCtrl as ctrl"> <span>{{ctrl.remaining()}} of {{ctrl.todos.length}} remaining</span> [ <a href ng-click="ctrl.archive()">archive</a> ] <ul> <li ng-repeat="todo in ctrl.todos"> <label> <input type="checkbox" ng-model="todo.done"> <span class="done-{{todo.done}}">{{todo.text}}</span> </label> </li> </ul> <form ng-submit="ctrl.addTodo()"> <input type="text" ng-model="ctrl.todoText" size="30" placeholder="what needs to be done?"> <input type="submit" value="Add"> </form> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script> angular.module('myApp', []).controller('TodoCtrl', function() { const myList = this; myList.todos = [ {text: 'grab a coffee', done: true}, {text: 'code with passion', done: false}, {text: 'learn AngularJS', done: false}, {text: 'learn Angular 2', done: false}, {text: 'create new ng1/ng2 apps', done: false}, {text: 'write new ng1/ng2 tutorials', done: false}, {text: 'contribute in Angular repositories', done: false}, {text: 'create a new JavaScript SPA framework', done: false} ]; myList.addTodo = () => { myList.todos.push({text: myList.todoText, done: false}); myList.todoText = ''; }; myList.remaining = () => { let count = 0; angular.forEach(myList.todos, (todo) => { count += todo.done ? 0 : 1; }); return count; }; myList.archive = () => { let oldTodos = myList.todos; myList.todos = []; angular.forEach(oldTodos, (todo) => { if (!todo.done) { myList.todos.push(todo);} }); }; }); </script> </body> </html>


angularJS: create components

<!doctype html> <html ng-app="myApp"> <head> <title>work hard, be kind, do more</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> </head> <body> <tabs> <pane title="Localization"> <span>Date: {{ '2017-03-22' | date:'fullDate'}}</span><br> <span>Currency: {{123456789 | currency}}</span><br> <span>Number: {{98765.4321 | number}}</span><br> </pane> <pane title="Pluralization"> <div ng-controller="ScalpCounter"> <div ng-repeat="scalpCount in scalps"> <ng-pluralize count="scalpCount" when="scalpForms"></ng-pluralize> </div> </div> </pane> </tabs> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script> angular.module('myApp', []).controller('ScalpCounter', ['$scope', '$locale', function($scope, $locale) { $scope.scalps = [0, 1, 2, 3, 4, 5, 6]; if ($locale.id === 'en-us') { $scope.scalpForms = { 0: 'no scalps', one: '{} scalp', other: '{} scalps' }; } else { $scope.scalpForms = { 0: 'keine Kopfhaut', one: '{} Kopfhaut', other: '{} Kopfhäute' }; } }]).directive('tabs', function() { return { restrict: 'E', transclude: true, scope: {}, controller: function($scope, $element) { let panes = $scope.panes = []; $scope.select = (pane) => { angular.forEach(panes, (pane) => { pane.selected = false; }); pane.selected = true; } this.addPane = (pane) => { if (panes.length === 0) { $scope.select(pane); } panes.push(pane); } }, template: ` <div> <ul class="nav nav-tabs"> <li ng-repeat="pane in panes" ng-class="{active:pane.selected}"> <a href="" ng-click="select(pane)">{{pane.title}}</a> </li> </ul> <div class="tab-content" ng-transclude></div> </div> `, replace: true }; }).directive('pane', function() { return { require: '^tabs', restrict: 'E', transclude: true, scope: { title: '@'}, link: function(scope, element, attrs, tabsController) { tabsController.addPane(scope); }, template: ` <div class="tab-pane" ng-class="{active: selected}" ng-transclude> </div> `, replace: true }; }); </script> </body> </html>


angular phonecat tutorial: some math

<!doctype html> <html ng-app="myApp"> <head> <title>angular phonecat</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> </head> <body> <p>1 + 1 = {{1 + 1}}</p> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script> angular.module('myApp', []); </script> </body> </html>


angular phonecat tutorial: controller

<!doctype html> <html ng-app="myApp"> <head> <title>angular phonecat</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> </head> <body ng-controller="PhoneListCtrl"> <ul> <li ng-repeat="phone in phones"> <span>{{phone.name}}</span> <span>{{phone.snippet}}</span> </li> </ul> <p>Total number of phones: {{phones.length}}</p> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script> angular.module('myApp', []).controller('PhoneListCtrl', ['$scope', function($scope) { $scope.phones = [ { name: 'Nexus S', snippet: 'fast just got faster with Nexus S.' }, { name: 'Motorolla XOOM with Wi-Fi', snippet: 'the next, next generation tablet.' }, { name: 'Motorolla XOOM', snippet: 'the next, next generation tablet.' } ]; }]); </script> </body> </html>


unit testing: controller

describe('PhoneListCtrl', function() { beforeEach(module('myApp')); it('should create a phones model with 3 phones', inject(function($controller) { let scope = {}; let ctrl = $controller('PhoneListCtrl', {$scope: scope}); expect(scope.phones.length).toBe(3); })); });


angular phonecat tutorial: component

<!doctype html> <html ng-app="myApp"> <head> <title>angular phonecat</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> </head> <body> <phone-list></phone-list> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> <script> angular.module('myApp', []).component('phoneList', { template: ` <ul> <li ng-repeat="phone in $ctrl.phones"> <span>{{phone.name}}</span> <p>{{phone.snippet}}</p> </li> </ul> `, controller: function PhoneListCtrl() { this.phones = [ { name: 'Nexus S', snippet: 'fast just got faster with Nexus S.' }, { name: 'Motorolla XOOM with Wi-Fi', snippet: 'the next, next generation tablet.' }, { name: 'Motorolla XOOM', snippet: 'the next, next generation tablet.' } ]; } }); </script> </body> </html>


unit testing: component

describe('phoneList', function() { beforeEach(module('myApp')); describe('PhoneListCtrl', function() { it('should create a phones model with 3 phones', inject(function($componentController) { let ctrl = $componentController('phoneList'); expect(ctrl.phones.length).toBe(3); })); }); });


Default Success Warning Important Info Inverse
B S W I ? O