Angular Routing Demo

WHAT'S ANGULAR.JS?

 

  • MVC Framework for web-apps in Javascript.
     
  • Provides a more structured way to organize your front-end app.
     
  • Makes your life easier (almost always).

CLIENT-SERVER ARCHITECTURE

Web 2.0

Server

Cliente

Business logic

BDDBB

HTML rendering

basic JS

HTML

CLIENT-SERVER ARCHITECTURE

Web Apps nowadays

Server

Business logic

DDBB

REST API

Business logic

JS + JQuery, AngularJS...

HTML

JSON

WHY ANGULAR?

Takes some of your business logic from the server to the client

Design patterns: MVC, Singleton...

SPA + JSON = Lower weight in requests = Better performance

Better code structure

Do more with less code

Powered by Google

Comunity

ANGULARJS VS REGULAR JS

HTML + JS

<ul id="myList">List:</ul>
var things = ["thing 1", "thing 2", "thing 3"];
var list = "";
var i = 0;
for (i = 0; i < things.length; i++) { 
    list += "<li>" + things[i] + "</li>";
}


document.getElementById('myList').innerHTML = list;

HTML + angularJS

<ul>
    <li ng-repeat="thing in things">{{thing}}</li>
</ul>
var things = ["thing 1", "thing 2", "thing 3"];

AND WHY NOT ANGULAR?

Performance against native apps (mobile, desktop)

SEO

POSsIBILITIES

AngularJS + HTML5 = Web Apps

AngularJS + Cordova / Phonegap = Mobile Apps

AngularJS + Node-Webkit = Desktop Apps

MVC

 

  • Model: Factory, Scope
     
  • View: HTML, Directives, Filters
     
  • Controller

Angular structure

HTML

DIRECTIVES

VIEWS

FILTERS

JS

FACTORY

CTRL

CONFIG

SERVICE

NO DOM!

$SCOPE

Comunicator

file tree

  • app
    • js
      • app.js
      • controllers.js
      • services.js
      • directives.js
      • filters.js
      • ​​vendor
        • ​angular.min.js
        • angular-route.min.js
    • css
      • style.css
    • partials
      • view1.html
      • view2.html
    • index.html
  • package.json

Folders

JS

CSS

HTML

Others

app.js

// Declare app level module
var myApp = angular.module('myApp', ['ngRoute']);


myApp.config(['$routeProvider', '$locationProvider',

    function ($routeProvider, $location) {

        $routeProvider.when('/view_1', {
            templateUrl: 'partials/view1.html',
            controller: 'HomeCtrl'
        });

        $routeProvider.when('/view_2', {
            templateUrl: 'partials/view2.html',
            controller: 'EditCtrl'
        });

        $routeProvider.otherwise({
            redirectTo: '/view_1'

        });
        
  }]);

index.html

<!doctype html>
<html ng-app="myApp">

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width", initial-scale=1.0/>
        <title>My App Web</title>
    
        <link rel="stylesheet" href="css/style.css" />
    </head>
    
    <body>

        <div ng-view></div>
    
       
        <!-- AngularJS core -->
        <script src="js/vendor/angular.min.js"></script>
        <script src="js/vendor/angular-route.min.js"></script>
    
        <!-- AngularJS app files -->
        <script src="js/app.js"></script>
        <script src="js/services.js"></script>
        <script src="js/controllers.js"></script>
        <script src="js/filters.js"></script>
        <script src="js/directives.js"></script>
    
        
    </body>

</html>

VIEW1.html

<h1>HI, I'M THE VIEW 1</h1>

VIEW2.html

<h1>HI, I'M THE VIEW 2</h1>

controllers.js

myApp.controller('View1Ctrl', ['$scope',
    function ($scope) {

  }]);

myApp.controller('View2Ctrl', ['$scope',
    function ($scope) {

  }]);

let's see it in action

directives

ng-model

<input type="text" ng-model="text">

<p>{{text}}</p>
  • Creates a variable
  • Two way binding
  • Accesible from the $scope
myApp.controller('View1Ctrl', ['$scope',
    function ($scope) {
        
  }]);

View 1

Let's see it

<input type="text" ng-model="text">

<button ng-click="hello()">SAY HELLO</button>
myApp.controller('View2Ctrl', ['$scope',
    function ($scope) {
        $scope.hello = function(){
            alert($scope.text);
        };
  }]);

View 2

Let's see it

ng-CLICK

Executes a function declared in the $scope when the user clicks

ng-repeat

Repeats an HTML component depending on an array

<ul>
    <li ng-repeat="thing in things">{{thing}}</li>
</ul>
myApp.controller('View1Ctrl', ['$scope',
    function ($scope) {
        $scope.things = ["thing 1", "thing 2", "thing 3", "thing 4"];
  }]);

Extra possibilities: apply filters, sorting...

OTHER DIRECTIVES

ng-show

ng-include

ng-animate

ng-touch

ng-change

ng-disabled

...

Controllers

$routeProvider.when('/home', {
            templateUrl: 'partials/home.html',
            controller: 'HomeCtrl'
        });
myApp.controller('HomeCtrl', ['$scope',
    function ($scope) {
        
  }]);

declaration

myApp.controller('HomeCtrl', ['$scope',
    function ($scope) {
        // SET
        $scope.text = "Hola";
        // GET
        var text = $scope.text;
  }]);

$scope

<input type="text" ng-model="text">
myApp.controller('HomeCtrl', ['$scope',
    function ($scope) {
        $scope.text = "Hola";
  }]);

NESTED CONTROLLERS

<div ng=controller="HomeCtrl">
    <div ng=controller="InputCtrl">
        <p>{{text}}</p>
    </div>
</div>
myApp.controller('InputCtrl', ['$scope',
    function ($scope) {
        $scope.text = "Hello";
  }]);
myApp.controller('HomeCtrl', ['$scope',
    function ($scope) {

        $window.alert("Hola");

  }]);

DEPENDENCY INJECTION

myApp.controller('HomeCtrl', ['$scope', '$window', '$location', 'myService', 'myFilter'
    function ($scope, $window, $location, myService, myFilter) {

        $window.alert("Hola");
        $location.path = "#/profile";

  }]);
myApp.controller('HomeCtrl', ['$scope', '$window',
    function ($scope, $window) {

        $window.alert("Hola");

  }]);

EXERCISE

Write an app where you can:

  • Load a default set of tasks
  • Create a new task
  • Delete a task
  • Filter the tasks

Services & factories

Services & factories

Business logic wrappers (http requests, local DDBB access...) 

They allow us to reuse code in different controllers (data validation, auth...)

Service: Instanciates a new object

Factory: Always references the same object

myApp.factory('AppOptions', function(){

    var dbVersion = 1;
    var gmapsApiKey = "API_KEY";

    return {
        getDBVersion: function () {
            return dbVersion;
        },
        getGMapsApiKey: function () {
            return gmapsApiKey;
        }
    }
 
});

factory

myApp.factory('GithubService', ['$http',
    function ($http) {
        var github_api = 'https://api.github.com';
        return {
            getUser: function (username) {
                return $http.get(github_api + '/users/' + username);
            },
            getUserRepos: function (username) {
                return $http.get(github_api + '/users/' + username + '/repos?sort=pushed');
            }
        }
    }]);

+ factory

myApp.controller('HomeCtrl', ['$scope', 'AppInfo', 'GithubService',
    function ($scope, AppInfo, GithubService) {

        var getGithubUser = function (username) {
            GithubService.getUser(username).success(function (data) {
                $scope.githubUser = data;
            });
        };

        getGithubUser('uesteibar');

        $scope.dbVersion = AppInfo.getDBVersion();
        
  }]);

WE INJECT THEM

exercise

Write an app where you can write a github user in a search field, and fetch the user data from github.

AND NOW... WHAT?

  • Routes with params
  • http CRUDs (Services)
  • External modules
  • Storage (Local, Session, ng-cache...)
  • Custom directives

Workshop docs

Exercises and examples: https://github.com/uesteibarworkshops

Day-04 Angular 3.0

By Tarun Sharma

Day-04 Angular 3.0

  • 932