AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners...

43
AngularJS Part 2 Jasmin , Software Architect Kristijan Horvat, Software Architect

Transcript of AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners...

Page 1: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

AngularJS Part 2

Jasmin , Software Architect Kristijan Horvat, Software Architect

Page 2: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

10. Server communication

• $http built-in service

• similar to jQuery's $.ajax method

• can be called in 2 ways:

• via configuration Object, such as $http({...})

• via available shorthand methods, such as $http.get(...)

Page 3: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

10.1 $http service sample

$http.get('/url')

.success(function (data, status, headers, config) {

})

.error(function (data, status, headers, config) {

});

Page 4: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

10.2 Promise based callbacks

• success and error callbacks are invoked asynchronously • based on the deferred/promise API exposed by the built-in

$q service $http.get('/url')

.then(function (response) {

// success

}, function (reason) {

// error

});

Page 6: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

11. Directives

• extend HTML's capabilities

• provide powerful logic to an existing specific element

• be an element itself and provide an injected template with powerful logic inside

• 2 types: • built-in (ng-*)

• custom

Page 7: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

11.1 ng-repeat

• copies an element and duplicates it whilst dynamically filling it with each object's data in an array

• if an item is removed from the source array, Angular will update the DOM automatically

<ul>

<li ng-repeat="item in main.items">

{{ item }}

</li>

</ul>

Page 8: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

11.2 ng-model

• 2-way data binding between $scope model and

• if a bound model or a model property doesn't exist inside $scope, Angular will just initialize it.

<input type="text" ng-model="main.message">

<p>Message: {{ main.message }}</p>

Page 9: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

11.3 ng-click

• one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click and bind the

relevant listeners as well as take care of removing them when DOM is disposed

• scoped and not global (which functions would need to be to be available for onclick)

<input type="text" ng-model="main.message">

<a href=" ng-click="main.showMessage(main.message);">

Show my message</a>

Page 10: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

11.4 ng-href/ng-src

• Angular takes care of any browser quirks with dynamically setting a href and src value

<a ng-href="{{ main.someValue }}">Go</a>

<img ng-src="{{ main.anotherValue}}" alt=">

Page 11: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

11.5 ng-class

• different syntax - an object with properties and values • Angular will add/remove classes based on the expression

provided, along with a standard class attribute

<div class="notification" ng-class="{

warning: main.response == 'error',

ok: main.response == 'success'

}">

{{ main.responseMsg }}

</div>

Page 12: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

11.6 ng-show/ng-hide

• shows or hides the given HTML element based on the expression provided • done under the hood by adding the .ng-hide CSS class (display: none

!important) • no other difference apart from they do the opposite of each other

<a href=" ng-click="showMenu = !showMenu">Toggle menu!</a>

<ul ng-show="showMenu">

<li>1</li>

<li>2</li>

<li>3</li>

</ul>

Page 13: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

11.7 ng-if

• actually destroys the DOM and the $scope it creates • if the element needs recreating due to value changes, Angular will

create new $scope • improved performance, as removing elements via ng-if removes the

$scope, which in turn lowers the $$watchers count inside Angular, speeding up further $digest cycles

<div ng-if="!main.userExists">

Please log in

</div>

Page 14: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

11.8 ng-switch

• an ng-if on steroids • multiple chunks of HTML to swap in and out based on a single $scope value

<div ng-switch on="main.user.access">

<div ng-switch-when="admin">

<!-- code for admins -->

</div>

<div ng-switch-when="user">

<!-- code for users -->

</div>

...

</div>

Page 15: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

11.9 ng-view

• in single page applications (SPAs), the concept is just having one page that dynamically updates

• Angular delivers this via ng-view attribute on an empty HTML element (e.g. <div>)

• depending on the current route in the URL, different HTML is fetched via XMLHttpRequest and injected

• e.g. inject login.html when the page's location (URL) says myapp.com/#/login

Page 16: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

11.10 ng-include

• fetches, compiles and includes an external HTML fragment

• additional way to do templating aside from ng-view and custom directives

• template URL is by default restricted to the same domain and protocol as the application document

• further restrictions by CORS on all browsers and file:// protocol on some browsers

Page 18: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12. Custom directives

• one of the hardest concepts and APIs to grasp in Angular as they don't adhere to any software engineering concept

• Angular's way to start using the rapidly approaching (but future) Web Components standard, which introduces:

• Custom elements

• Shadow DOM

• Templating

Page 19: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12.1 Custom elements

• allow web developers to define new types of HTML elements

• a declarative approach to encapsulating behavior • solve the problem of reusable and boilerplate code • in Angular are less strict than the Web Components

specification as Angular supports older versions of IE

<my-element></my-element>

Page 20: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12.2 Shadow DOM

• allows DOM to be nested inside DOM

• one main document and small pockets of other nested documents

• HTML, CSS and JavaScript scoping and encapsulation

• Angular emulates Shadow DOM

Page 21: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12.3 Templating

• directives can define their own HTML templates:

• an HTML string

• an external resource (template file)

• a <script> element with the template inside

• all templates that are initially loaded by Angular go straight into the $templateCache and are fetched from there for the lifetime of the application

Page 22: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12.4 Directives in HTML

• four ways to use directives in Angular - custom elements, custom attributes, class names and comments:

<my-element></my-element>

<div my-element></div>

<div class="my-element"></div>

<!-- directive: my-element -->

Page 23: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12.5 Directive declaration

angular.module('app')

.directive(‘myElement', function (...DI...) {

return {

restrict: 'EA',

replace: true,

templateUrl: 'my-element.html',

controllerAs: 'something',

controller: ...,

scope: {},

link: function ($scope, $element, $attrs) {

...

}

};

});

Page 24: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12.5.1 Directive properties - restrict

• a restrict property defines which of the 4 shapes is allowed: • E element • A attribute • C class • M comment

• by default, if not specified differently, all directives are set to 'EA' (Element, Attribute)

Page 25: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12.5.2 Directive properties - replace

• replaces the original Directive's element

• e.g. If <some-directive></some-directive> is used and replace is set to true, once rendered Angular will remove the original custom element declaration, leaving just the injected content

Page 26: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12.5.3 Directive properties controller & controllerAs

• assigns an existing controller or creates a new one • e.g. If MainController already exists, one can assign it

using controller: 'MainCtrl

• e.g. If a new controller is needed, it can be declared by using controller: function () {...}

• controllerAs same as mentioned before, if defined, any Controller references inside template would use controller name specified by this property

Page 27: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12.5.4 Directive properties template

• an HTML String that Angular then compiles into live DOM

template: '<div>' +

'<ul>' +

'<li ng-repeat="item in vm.items">' +

'{{ item }}' +

'</li>' +

'</ul>' +

'</div>'

Page 28: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12.5.5 Directive properties templateUrl

• an external resource or a <script> element with HTML

templateUrl: 'items.html‘

<script type="text/ng-template" id="/hello.html">

<ul>

<li ng-repeat="item in vm.items">

{{ item }}

</li>

</ul>

</script>

Page 29: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12.5.6 Directive properties transclude

• wraps outside elements: <my-directive>

...html to wrap...

</my-directive>

• i ...

<ng-transclude>

... html to wrap appears here...

</ng-transclude>

...

Page 30: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12.5.7 Directive properties scope

• scope: true directive creates a new scope that

parent

• scope: false directive uses scope of the

• scope: {} directive creates a new isolated scope,

Page 31: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12.5.7 Directive properties scope

• isolated scope with passing specified values from the parent attributes on

scope: { someValue: "@", // - Text binding / one-way binding someValue2: "=", // - Direct model binding / two-way binding someMethod: "&" // - Behaviour binding / Method binding } • these qualifiers can also be specified with a different name, e.g.

"=someOtherValue2"

Page 32: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12.5.7 Directive properties scope

<my-directive

someValue="{{parentValue1}}"

someOtherValue2="parentValue2"

someMethod="parentMethod()"

></my-directive>

Page 33: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

12.5.8 Directive properties link

• a function which is called after the element is compiled and injected into the DOM

• perfect place to do "post-compile" logic, as well as non-Angular logic

• DOM manipulation is never used in a Controller, the link function is created as a utility for this

• able to inject $scope, the root element of Directive's template $element, and an object called $attrs which contains DOM element attributes

Page 35: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

13. Routing

• delivers the Single Page Application (SPA) methodology

• application's state determined by router, which responds to changes to the application location (the URL)

• available as an optional module (ngRoute), since not everybody is using it and many are using a third party option (AngularUI Router)

Page 36: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

13.1 Routing syntax

$routeProvider

.when('/inbox', {

templateUrl: 'views/inbox.html',

controller: 'InboxController',

controllerAs: 'inbox'

})

.otherwise({

redirectTo: '/inbox'

});

Page 37: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

13.2 Routing controlled content

• template specified in the routing configuration is rendered via ng-view directive

• the ng-view attribute sits in the "middle" of the app (usually standard layout is around it), and at any changes to the window's location, Angular will reference the router to see if it needs to inject a new template

<div ng-view></div>

Page 38: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

13.3 Dynamic routing & $routeParams

/inbox/email/20999851

.when('/inbox/email/:id', {

templateUrl: 'views/email.html',

controller: 'EmailController',

})...

function EmailCtrl ($routeParams, EmailService) {

EmailService.get($routeParams.id)

...

Page 39: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

13.4 Routing urls

• route url is based on the # (hashtag) for non HTML5 browsers

• $locationProvider.html5Mode(true) is used to tell Angular to use HTML5 strategy and work with nice urls

• in HTML5 mode, if a browser refresh (F5) is triggered, a web server needs to be configured in a way to able to serve the whole SPA (index.html) from any possible route

Page 41: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

14. Scaffolding automated development processes

• project structure • distribution • minification • including and adding script/link tags for newly added files • refreshing browser upon changing HTML, JavaScript or Css • testing • JavaScript hinting/linting • compiling Sass/Less into Css • ...and much more...

Page 42: AngularJS Part 2 - mono.hr · 11.3 ng-click • one doesn't have to manually bind event listeners to multiple elements • Angular will evaluate the expression(s) inside the ng-click

14. Scaffolding key parts

• NodeJS for environment

• BowerJS for packaging dependencies

• Gulp/Grunt for automation of processes

• Karma/Jasmine/Mocha/Chai... for testing