AngularJS

Component, Services, UI-Router

  • Component
  • Services
  • UI-Router

Agenda

Components

When not to use Components

module.component()

// Params
// component name
// component definition object (CDO)

Example
.component(“myComponent”, CDO);

<my-component></my-component>

Component Definition object Properties

  • •bindings
  • •controller
  • •controllerAs
  • •require
  • •template
  • •templateUrl
  • •transclude

Component Definition object Properties

import template from './button.html';
import controller from './button.controller';

export const buttonComponent = {
  bindings: {
    buttonDisabled: '<',
  },
  template,
  controller,
  transclude: true
};

Practice

import template from './button.html';
import controller from './button.controller';

export const buttonComponent = {
  bindings: {
    buttonDisabled: '<',
    buttonType: '@',
    buttonClass: '@',
    onClick: '&'
  },
  template,
  controller,
  transclude: true
};

Bindings

class ButtonController {
}

export default ButtonController;

Bindings

controller

import { buttonComponent } from './button.component';
import './button.scss';

export const buttonModule = angular
        .module('button', [])
        .component('button', buttonComponent)
        .name;

module

<button class="button"
        ng-attr-type="{{ $ctrl.buttonType }}"
        ng-class="[
          $ctrl.buttonClass,
          { 'disabled': $ctrl.buttonDisabled }
        ]"
        ng-disabled="$ctrl.buttonDisabled"
        ng-click="$ctrl.onClick()">
  <div ng-transclude></div>
</button>

view

New lifecycle Hooks

Components as route templates

angular.module(“app”, [“ngRoute”])
	.component(“home”, {
		template: `<h1>Hello</h1>`
	})
	.config(function($routeProvider) {
		$routeProvider.when(“/”, {
			template: `<home></home>`
		})
	});

Resolve property

angular.module(“app”, [“ngRoute”])
	.component(“home”, {
		template: `<h1>Hello, {{$ctrl.user.name}}!</h1>`,
		bindings: {
			user: “<”
		}
	})
	.config(function($routeProvider) {
		$routeProvider.when(“/”, {
			template: `<home user=“$resolve.user”></home>`,
			resolve: { user: function($http) {…}	}
		})
	});

Services

1.Why to Use Services

2.Create and Use Services

    §factory

    §service

    §provider

    §constant

    §value

3.The List of Built-in AngularJS Services

4.Decorating Services

Why to Use Services

•Lots of built-in functionality

•Best place to implement reusable code

•Hold, share data and state

•Communicate with Server

•Manage complexity

•Clean maintainable code

Services

•Services are singleton objects

•Built-in Services

    –$http

    –$filter

    –$resource

•Custom Services

    –you can create your own services

Methods

–module.service()

–module.factory()

–module.provider()

 

–module.constant()

–module.value()

Examples

// Example
angular.module(“app”).service(“myService”,  myService);
function myService() {
       this.value = …
});
class UsersService {
  constructor($state) {
    this.$state = $state;
  }

  ...
}

UsersService.$inject = [
  '$state'
];

export default UsersService;

Examples

.value(“myVar”,  10);
.value(“Backbone”, Backbone);
.value(“rankSrv”, {
	retriveRank: function() {…}
});

.constant(“PI”, 3.14);
.constant(“constants”, {
	APP_TITLE: “Task Manager”,
	APP_DESCR: “Track the tasks and users”,
	APP_VERSION: “1.0”
})

Built-in Services

UI-Router

<script src=“angular.js”></script>
<script src=“angular-ui-router.js”></script>
angular.module(“app”, [“ui.router”])

UI-Router Components

•Services

    –$stateProvider

    –$stateParams

    –$state

    –$urlRouterProvider

 

•Directives

    –ui-view

    –ui-sref

    –ui-sref-active

State Features

•Based around $stateProvider – similar to $routeProvider

•URL is optional

•Support Route Resolvers

•Nested States (parent/child)

•Multiple Views

ui-view

•Renders the view of a “state”

•Placeholders

•Similar to: ng-view

$stateProvider and $urlRouterProvider

angular.module(“app”, [“ui.router”]).config(appConfig);

function appConfig($stateProvider, $urlRouterProvider) {
$stateProvider
    .state(“start”, {
      url: “/list”,
      templateUrl: “start.html”,
      controller: “Main”,
      controllerAs: “$ctrl”,
      resolve: {
  	initialData: function(api) { return api.getStartData();  }      
     }
    });
$urlRouterProvider.otherwise(“/”);
});

PRACTICE

3 Ways to Activate a State

ui-sref & ui-sref-active

<a ui-sref=“home” ui-sref-active=“active”>Home</a>
<a ui-sref=“userList” ui-sref-active=“active”>Users</a>
<a ui-sref=“taskList” ui-sref-active=“active”>Tasks</a>

$state.go()

<button ng-click=“$ctrl.navigate(‘home’)”>Home</button>

.controller(“Home”, function($state) {
    let $ctrl = this;

    $ctrl.navigate = function(toState) {
        $state.go(toState);
    };
});

$state.reload()

<button ng-click=“$ctrl.refresh()”>Refresh</button>

.controller(“Home”, function($state) {
    let $ctrl = this;

    $ctrl.refresh = function() {
        $state.reload();
    }
});

$stateParams

$stateProvider
    .state(“edit”, {
      url: “/edit/:id”,
      templateUrl: “edit.html”,
      controller:  function($stateParams) {
        let $ctrl = this;
		 $ctrl.id = $stateParams[“id”];
		…
     }
    })
});

<a href=“#!/edit/1”>Edit Task</a>
<a ui-sref=“edit({id: 1})”>Edit Task</a>
$state.go(“edit”, {id: 1});

URL Examples

/edit/:id
/edit/{id}
// ! cannot use regex capture groups
/edit/{id: [0-9a-fA-F]{6}}
/list?sort=a

Nested States

•UI-Router Supports Nested States

•Dot Notation

•Child Inherits from Parent (URL, custom data object)

•Abstract

     –Can have child states but not get activated itself

     –Must contain their own ui-view

Nested States (Parent)

$stateProvider
	.state(“user”, {
		// an abstract template can never be directly 			
		// activated, but can set up descendants 
		// that are activated
		abstract: true,		
		url: “/user”,
		templateUrl: “user.html” // must contain ui-view
	});

<div ui-view></div>

Nested States (Child)

$stateProvider
	.state(“user.cost”, {
		// appended urls
		url: “/cost”, 		// will be “/user/cost”
		// or
		// absolute urls
		url: “^/cost”, 		// will be “/cost”
		templateUrl: “user-cost.html”,
		controller: “Cost”,
		resolve: {…}
		}
	});

State Change Events

$rootScope.$on(“$stateChangeStart”, 
function( evt, toState, toParams, fromState, fromParams) {
    // prevent state from completing
    evt.preventDefault();
})

•$stateChangeStart

•$stateNotFound

•$stateChangeSuccess

•$stateChangeError

View Load Events

•$viewContentLoading

•$viewContentLoaded

Multiple Named Views

Named views allow you to have more than 1 ui-view per template

<div>
    <div ui-view=“general"></div>
    <div ui-view=“cost"></div>
    <div ui-view=“notes"></div>
</div>

Multiple Named Views

$stateProvider
    .state(“users”, {
	views: {
	    “general”: {
		template: “<h4>General</h4>”,
	        controller: function() {} 
	    },
	    “cost”: {
	        templateUrl: “users/user-cost.html”
	    },
	    “notes”: {
	        template: “<h4>Notes</h4>”,
	        resolve: { … } 
	    }
	}
});

AngularJS

By Oleg Rovenskyi

AngularJS

Component, Services, UI-Router

  • 483