- angular 101 -

From Zero to Angular in one session

Table of contents

01

What is Angular?

02

Why angular?

03

best practices

04

angular vs jquery

05

angular basics

06

my first app

07

conclusions

live preview

09

10

credits

my tips

08

01

What is

Angular?

First of all...

what is a framework?

in one word:

a wrapper

is designed to enclose something

like a wrapper of

a candy

hence, Angular is a structural framework for dynamic web apps

angular is what html would have been, had it been designed for applications

some features that makes angular a good choice

100% javascript and client side

We separate the client server, to keep separate data

Reusable components

why make boilerplate code, being able to reuse what already exists? made by you or by other

single page apps

It executes in a single page, thus achieving a user experience closer to a desktop application

all this without refreshing the page or changing the url

MVC architecture

we can divide the code in parts, maintaining the order and reusable code

two way data-binding

It's continuously observing the changes that occur in both the View and the Model and synchronize data between them

what is not angular

Is not for make videogames. there are specific alternatives for that

 

like panda

or phaser

is not one way data-binding

is not a library, is a framework. a library only serve an specific purpose (slider, animations...)

you're ready to learn why use angular!

02

why

Angular?

why not?

Have a lot of modules made by the community

install and use it

don't do the work who someone else has already done for you

all the tricks that you can need, google has it

Have a lot of documentation and milions of examples in google

google has a solution for your problem because someone had the same

Angular works great with a JSON API delivered from the server

with mean in the back,

delivers better performance than a RoR o Python

write less code

<html ng-app="helloApp">
<body ng-controller="HelloCtrl">
<p>Hello {{name}}! How are you doing today?</p>
<label>Name: </label><input ng-model="name">
</body>
</html>

Lovely, is not it?

var app = angular.module("helloApp", []);
app.controller("HelloCtrl", function($scope) {
$scope.name = "";
});

html

js

in a few minutes you can have a

hello world

working

what for use it?

some examples...

dynamic

like ga.me

beautiful website made

with angular

integrates socket.io for

real-time chat

play social games with

web apps

your friends in pc,

tablet or mobile

dynamic

like lorempicsum

beautiful website made

with angular 1.1.5

dynamic placeholder with

5 different cartoons

Copy the URL by clicking

on the image made

with jquery zclip

website

dynamic

like mealshaker

beautiful ios app made with

angular and cordova

dynamic place to eat using

our location

shake the phone to find

an incredible place

mobile app

(or not)

then, we can view the difference between angular and jquery

03

vs

Angular

jquery

first, this is a comparative to know the difference between the two

let's compare a

in both languages

hello world

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ej Hola Mundo desarrollado en jQuery</title>
</head>
<body>
    <h1>Hola</h1>
        <form>
            ¿Cómo te llamas? <input type="text" id="nombre">
        </form>
    <script src="js/jquery.js"></script>
    <script>
    $(function(){
        var campoTexto = $("#nombre");
        var titular = $("h1");
        campoTexto.on("keyup", function(){
            titular.text("Hola " + campoTexto.val());
        });
    });
    </script>
</body>
</html>

jquery

<!DOCTYPE html>
<html lang="en" ng-app>
<head>
    <meta charset="UTF-8">
    <title>Ej Hola Mundo desarrollado en AngularJS</title>
</head>
<body>
    <h1>Hola {{nombre}}</h1>
        <form>
            ¿Cómo te llamas? <input type="text" ng-model="nombre">
        </form>
</body>
</html>

angular

did you see the                       ?

difference

<form>
¿Cómo te llamas? <input type="text" id="nombre">
</form>
<form>
¿Cómo te llamas? <input type="text" ng-model="nombre">
</form>

input

angular

jquery

01

script

02

<script>
$(function(){
    var campoTexto = $("#nombre");
    var titular = $("h1");
    campoTexto.on("keyup", function(){
        titular.text("Hola " + campoTexto.val());
    });
});
</script>

not have

jquery

you need around 90% less code to do the same thing with JQuery

angular has implemented ng-model directive: links application data to html elements

second, we're gonna to know when is best to use angular or jquery

if you are building a normal web app with views and you need a little bit of interactivity on the page ...

use

jquery

If you need a lot of interactivity and better user experience ...

use

angular

but you'll need to have a REST API or something similar to consume data from somewhere

angular does everything that jQuery does and much more, but jQuery doesn't do everything that angular does

let's start with

angular

04

basics

Angular

let's start !

how angular runs?

angular will run when the entire page is finished loading

When the page is loaded, Angular will visit each of the elements of your HTML document. If an item contains a directive, it will attach a behavior.

The first directive that angular need to find is the                    directive

Angular will associate our application with the element where find the directive ngApp

ngapp

remember that angular only will give functionality to their child elements

<body>
    <div id="app" ng-app>
      <h1>Hello from Angular</h1>
    </div>
</body>
<body ng-app>
    <div id="app">
      <h1>Hello from Angular</h1>
    </div>
</body>

this only will affect to div#app

this will affect to body and his child elements

of course, we can define a name for our app instead of use the default one with ngapp

<div id="app" ng-app>
<div id="app" ng-app='myApp'>

in resume

you must put in your html the ngapp directive

otherwise, the app will not run

html have limited tags, what happen if we want a                       tag?

<weather>

the                       is for create new dom elements

directives

<weather>

<div weather="sunny">

or

if you look any app made with angular, you will see ng tags

these are directives provided by angular

For example, we can use the directive                   to tell an element that must execute a function when you click on it

ngclick

<button ng-click="runWhenButtonClicked()"></button>
<div ng-click="runWhenDivClicked()"></div>

shh... there's a lot of directives included in angular!

we use lowerCamelcase to reference to the directive

however, when we use it in html, we use kabob (ng-click)

both refer to the same thing, angular automatically makes the conversion from one to another

directives are what make angular so powerful

We're going to learn to create our own directives later

in resume

The directives make it possible to extend HTML with custom functionality

how do you evaluate data in your html?

we use                             for that

expressions

<h3>Double the count is: {{ 2 * count }}</h3>

We can set variables, call functions, variables read, do math, etc

We can also use them in our own templates

<a ng-click="shouldShowDiv = !shouldShowDiv">Show content below</a>
<div ng-show="shouldShowDiv">WWill show if <em>shouldShowDiv</em> is true</div>
<div ng-hide="shouldShowDiv">Will hide if <em>shouldShowDiv</em> is not true</div>

how we tell angular where is our application written in angular?

we need to tell using

angular.module()

we can do two main operations when we work with a module:

create a new module or setter

retrieve an existing module or getter

01

02

angular.module('myApp', []);
angular.module('myApp');

can put our app in his stead using ngapp

We may think that a car is a collection of modules

The car consists of separate modules such as seat belts, engine, wheels, etc.

They are working jointly performing individual tasks

our app

module

in resume

a module it's nothing more than a collection of objects that define a specific functionality

we grouped all in a module to reuse it

how do you make your variables accesible from the browser?

for that, we use

$scope

an important detail is: it works in both ways

the view can charge variables and variables can be changed in the view

Scope is the link between views and controllers

.controller('otroCtrl', function($scope){
  $scope.algo = "probando scope...";
  $scope.miDato = "otra cosa..."
});
<p>{{ algo }}</p>

controller

view

we can change scope data from view

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

in resume

scope is for share data between the view and the model

how do you define the functionality of the page?

you could use

controllers

every controller has his own scope object

you should use for mantain $rootscope clean

angular.module('myApp')
.controller('HomeController', function($scope) {
  $scope.name = 'Cory';
});
<div ng-controller='HomeController'>
    <p>{{name}}</p>
</div>

it's easy to use

in resume

A controller is a piece of code that connects scopes using models and views

how do you obtain the dependencies?

injecting dependencies

this is how you tell angular which dependencies need to use to facilitate us when we need them

if we have a weather service, and we want to have in our controller ...

// imagina que tenemos algunos servicios...
angular.module('fullstack.services', [])
  // algo de código que define los servicios aqui
  .service('WeatherService', function() {
    // implementa el servicio aquí
  });
);

// y queremos usar estos servicios en nuestros controladores
angular.module('fullstack.controllers', ['fullstack.services'])
  // aquí tenemos el servicio WeatherService disponible
);

we have weatherservice accessible from the controller

easy!

in resume

inject dependencies is mandatory. you must do if you have your app splitted in modules

how do you make http requests?

for that purpose, we're go to use

services

they are objects that perform common tasks to various parts of the system

factories

or

if you're going to make requests in many places of your code, you should use a service or a factory

module.factory('userService', function(){
    var fac = {};
    fac.users = ['John', 'James', 'Jake'];      
    return fac;
});
angular.module('myApp.controllers')
.controller('PeopleController',['$scope', 'userService',
  function($scope, servie) {
  $scope.people = service.users;
}]);

here, you insert your code

here, you inject your factory and use it

in resume

the services are for simple logic

the factories are for complex logic

so, let's go create

our first app

05

my first

app

we saw hello world example, so let's do another app

we're gonna to do a dynamic web with a bootstrap template

this, specifically

01

download

download the template in the previous link

don't worry about directory structure, we'll view later

02

split

divide in parts the html

remember: keep in mind that repeated areas must be shared templates

03

bower

download the necessary dependencies with bower

like angular, bootstrap and jquery

04

structure

reorder your html.

divide into folders

remember: you're going to view about best practices later

but let's view next slide ...

.
├── app
│   ├── app.js
│   ├── app.routes.js
│   ├── app.module.js
│   ├── partials
│   │     ├── related.partial.html
│   │     ├── footer.partial.html
│   │     ├── stories.partial.html
│   │     ├── home.partial.html
│   │     └── sidebar.partial.html
│   ├── controllers
│   │       ├── home.controller.js
│   │       ├── social.controller.js
│   │       └── related.controller.js
│   ├── directives    
│   │       └── social.directive.js
│   └── directives
│           └── request.factory.js
├── assets
│     ├── css
│     ├── img 
│     └── js
├── json
│     ├── related.json
│     └── stories.json
├── bower_components 
└── index.html

this is our directory structure

partials

components

has two important parts

partials contains the html divided in parts

components contains the angular modules

05

app

create your app.js and app.module.js

angular.module('demo', []);

for now, doesn't have any module injected

angular.module('demo.module', []);

app.js

app.module.js

next, create app.routes.js

angular.module('demo.routes', []);

app.routes.js

we have our app.js, app.module.js and app.routes.js

let's go to inject the modules!

angular.module('demo', [
    // App module
    'demo.modules'
]);
angular.module('demo.module', [
    // App routes
    'demo.routes'
]);

app.js

app.module.js

inject into app.js our main module, which is going to contain all the components

inject into app.module.js the app routes

angular.module('demo.routes', [
    // Angular routes
    'ngRoute'
]);

app.routes.js

don't forget to inject angular routes!

if you don't insert ngroute, routes will not work

and finally, app.routes.js

angular doesn't contain inside his code this module neither any

06

html

you have to define in html ngapp

<body ng-app="demo"></body>

include in your index.html (which should be empty) the sidebar and footer

<body ng-app="demo">
    <div ng-include="'/app/partials/sidebar.partial.html'"></div>
    <div ng-include="'/app/partials/footer.partial.html'"></div>
</body>

07

routes

let's create our routes for view our amazing templates!

angular
    .module('demo.routes', [
        // Angular routes component
        'ngRoute'
    ])
    .config(['$routeProvider', function ($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl: "/app/partials/home.partial.html"
    })
    .when("/featured", {
        templateUrl: "/app/partials/featured.partial.html"
    })
    .when("/stories", {
        templateUrl: "/app/partials/stories.partial.html"
    })
    .otherwise({
        redirectTo: '/'
    });
}]);

we're going to see in detail

.config(['$routeProvider', function ($routeProvider) {
$routeProvider
    .when("/", {
        templateUrl: "/app/partials/home.partial.html"
    })
.otherwise({
    redirectTo: '/'
});

1

2

3

1. introduce your desired url. remember that you can use dynamic urls using :param

2. with templateUrl we tell where to find the template to paint

3. with otherwise, angular will redirect to "/" in other cases

finally, introduce ng-view attribute

<body ng-app="demo">
    <div ng-include="'/app/partials/sidebar.partial.html'"></div>
    <div ng-view></div>
    <div ng-include="'/app/partials/footer.partial.html'"></div>
</body>

introduces into html the partial template depending on the route

hooray!

you've got your dynamic templates runing now

but this don't have any angular power...

so, let's go creating controllers, directives and services!

08

controller

create a module named demo.controller.social

next, create a controller named socialcontroller

angular
	.module('demo.controller.social', [])
	.controller('SocialController', SocialController);

SocialController.$inject = ['$scope'];
function SocialController($scope, request){
	
}

remember inject in demo.module

we're going to insert an array and display with scope

function SocialController($scope, request){
	$scope.data = [
                        {title: 'Twitter'},
                        {title: 'Google+'},
                        {title: 'Facebook'}
                      ];
}

we introduce manually the data, later we're go to view to obtain from a json

create a new controller named postcontroller (in a new js file)

angular
	.module('demo.controller.post', [])
	.controller('PostController', PostController);

PostController.$inject = ['$scope'];

function PostController($scope){
	
}

09

directive

let's create our own html element for social links

angular
	.module('demo.directive.social', [])
	.directive('mdSocial', mdSocial);

function mdSocial() {
	var directive = {
		transclude: true,
		restrict: 'EA',
		template: '<a href="#">{{social.title}}</a> <small class="text-muted">|</small> '
	};
	return directive;
}

1

2

1. type of directive

2. html template

there are 4, but only two are important: element (E), attribute (A),

we introduce the html and it can have expressions inside

for use, we can use an element

or an attribute

<md-social></md-social>
<div md-social></div>

10

factory

we're going to create the factory for use in postcontroller

angular
	.module('demo.factory.request', [])
	.factory('requestFactory', requestFactory);

requestFactory.$inject = ['$http'];

function requestFactory($http) {
}

alright, let's go with http request!

angular
	.module('demo.factory.request', [])
	.factory('requestFactory', requestFactory);

requestFactory.$inject = ['$http'];

function requestFactory($http) {
	function get() {

	};
}

first, we're going to create a function inside. in this manner, we can have all requests inside with different name

second, add a parameter for introduce your json url and for obtain data to function parameters

angular
	.module('demo.factory.request', [])
	.factory('requestFactory', requestFactory);

requestFactory.$inject = ['$http'];

function requestFactory($http) {
	function get(url, success) {
	};
}

success is data you're going to receive

angular
	.module('demo.factory.request', [])
	.factory('requestFactory', requestFactory);

requestFactory.$inject = ['$http'];

function requestFactory($http) {
	function get(url, success) {
		var get = $http.get(url);
		get.success(success);
		get.error(function() {alert('error')});
	};
	return {
		'get': get
	};
}

third, insert the http request like angular explains

we can use http alone and introduce inside the type of request

$http({
  url: '...',
  method: 'GET'
});

success will save data if is ok

error will alert you if is there any error

use for have the possibility to have multiple functions and use at the same time

inject the factory in your controller and let's make the request

angular
	.module('demo.controller.post', ['demo.factory.request'])
	.controller('PostController', PostController);

PostController.$inject = ['$scope', 'requestFactory'];

function PostController($scope, request){
	request.get('/app/featured.json', function(data) {
		$scope.data = data.post;
	});
}

inject the factory module

there, too

use the get function from the factory

11

template

finally, only need to introduce expressions in our html for display the data into the scope

we need to tell the controller directive, don't forget!

<div class="row" ng-controller="PostController"> 
<h3>{{post.title}}</h3>

and you're done!

don't worry

this is not the end

but ...

06

live

preview

awww...

let's go to see in action!

07

best

practices

we're gonna look at:

directory structure

modules

controllers

directives

templating

comments

i18n

minification

other

services

directory structure

structure the app separating specific components of shared components

why?

1. locate easy all the components

2. reusable

3. separated static/vendor from app files

4. separated all specific components

5. you are free to use npm, bower and grunt/gulp

.
├── app
│   ├── app.js
│   ├── app.routes.js
│   ├── app.config.js
│   ├── app.module.js    // Main controller
│   ├── shared    // acts as reusable components
│   │   ├── sidebar
│   │   │   ├── controllers
│   │   │   │    ├── sidebar.controller.js
│   │   │   │    └── sidebar.controller.spec.js // Test
│   │   │   └── services
│   │   │        └── ...
│   │   └── header
│   │       ├── controllers
│   │       │    ├── header.controller.js
│   │       │    └── header.controller.spec.js // Test
│   │       └── header.routes.js
│   └── components    // each component is treated as a mini Angular app
│       └── product
│           ├── controllers
│           │    ├── product.controller.js
│           │    └── product.controller.spec.js // Test
│           └── partials
│                └── product.partial.html
├── assets
│   ├── css     // All styles and style related files
│   ├── img     // Images and icons for your app
│   └── js      // JavaScript files written for your app that are not for angular  
├── bower_components    // Directory with bower components installed
├── node_components    // Directory with node components installed
├── Gruntfile.js    // Grunt tasks
├── package.json    // Node package for install
└── index.html

modules

should be named with lowerCamelCase

For indicating that module      is submodule of module      you can nest them by using namespacing like:

ex: smyland.product

it's more easy to identify the parent

b

a

a.b

why?

Declare modules without a variable using the setter syntax

With one component per file, there is rarely a need to introduce a variable for the module

/* avoid */
var app = angular.module('app', ['ngAnimate']);
app.controller('SomeController', SomeController);

function SomeController() { }
/* recommended */
angular
    .module('app', ['ngAnimate'])
    .controller('SomeController', SomeController);

function SomeController() { }

use the same syntax for getters and setters

why?

controllers

do not manipulate DOM in your controllers. Use directives instead

controller's name is done by functionality and the substring Controller in the end

will be named uppercamelcase

ex: ProductController
// Don't do this

module.controller('MyCtrl', function ( ... ) {
  // ...
}
// Do this

module.controller('MyCtrl', MyCtrl);
function MyCtrl( ... ) {
  // ...
}

to prevent problems with minification, you should do:

// Solution - Explicit inject dependencies
module.controller('MainController', MainController);
function MainController($scope) {
    // ... 
};

MainController.$inject = ['$scope'];

we will see about minfication later

use the                        syntax over the classic controller with $scope syntax

1. it's hard to track where data is coming from

2. removes the use of $scope when no need for special operations. good preparation for angular 2

3. syntax closer to vanilla js

4. the dot rule: more contextual, easy to read and avoid issues that may occur without dot

<!-- avoid -->
<div ng-controller="Customer">
    {{ name }}
</div>
<!-- recommended -->
<div ng-controller="Customer as customer">
    {{ customer.name }}
</div>

controllerAs

why?

the                       syntax uses        inside controllers which get bound to $scope

controllerAs

this

function Customer($scope) {
    $scope.name = {};
    $scope.sendMessage = function() { };
}
function Customer() {
    this.name = {};
    this.sendMessage = function() { };
}

2. You can still bind to the View and still access $scope methods

1. controllerAs is syntactic sugar over $scope

but let's see the next section ...

why?

Use a capture variable for         when using the                         syntax

Choose a consistent variable name such as vm, which stands for ViewModel

controllerAs

this

function Customer() {
    this.name = {};
    this.sendMessage = function() { };
}
function Customer() {
    var vm = this;
    vm.name = {};
    vm.sendMessage = function() { };
}

The this keyword is contextual and when used within a function inside a controller may change its context. Capturing the context of this avoids encountering this problem

why?

Place bindable members at the top of the controller, alphabetized

makes it easy to read and helps you instantly identify which members of the controller can be bound and used in the View

function Sessions() {
    var vm = this;

    vm.gotoSession = function() {
      /* ... */
    };
    vm.refresh = function() {
      /* ... */
    };
    vm.search = function() {
      /* ... */
    };
    vm.sessions = [];
    vm.title = 'Sessions';
}
function Sessions() {
    var vm = this;

    vm.gotoSession = gotoSession;
    vm.refresh = refresh;
    vm.search = search;
    vm.sessions = [];
    vm.title = 'Sessions';

    function gotoSession() {/* */}

    function refresh() {/* */}

    function search() {/* */}
}

why?

define controllers along with their routes When a controller must be paired with a view

remember: If a View is loaded via other means besides a route, then use the controllerAs syntax in html

angular.module('app')
    .config(config);

function config($routeProvider) {
    $routeProvider
        .when('/avengers', {
          templateUrl: 'avengers.html'
        });
}
angular.module('app')
    .config(config);

function config($routeProvider) {
    $routeProvider
        .when('/avengers', {
          templateUrl: 'avengers.html',
          controller: 'Avengers',
          controllerAs: 'vm'
        });
}
<div ng-controller="Avengers as vm"></div>
<div></div>

use the original names of the controller's dependencies. This will help you produce more readable code:

function MyCtrl(s) {
  // ...
}

module.controller('MyCtrl', ['$scope', MyCtrl]);
function MyCtrl($scope) {
  // ...
}

module.controller('MyCtrl', ['$scope', MyCtrl]);

which is less readable than:

avoid writing business logic inside controllers. delegate to a model, using a service

angular.module('Store', [])
.controller('OrderCtrl', function ($scope) {

  $scope.items = [];

  $scope.addToOrder = function (item) {
    $scope.items.push(item);
  };

  $scope.removeFromOrder = function (item) {
    $scope.items.splice($scope.items.indexOf(item), 1);
  };

  $scope.totalPrice = function () {
    return $scope.items.reduce(function (memo, item) {
      return memo + (item.qty * item.price);
    }, 0);
  };
});

we will see business login in service later

templates

use                or                  instead of simple         to prevent flashing content

why here

avoid writing complex expressions in the templates

ng-bind

ng-cloak

{{ }}

set the       ,          ,          and           dynamically using:

$scope.divStyle { ... }
<div ng-style="divStyle">...</div>
<div ng-href="{{link}}">...</div>
<img ng-src="{{img}}">

src

ng-src

{{ }}

href

ng-href

ng-style

style

<div href="{{link}}">...</div>
<img src="{{img}}">

instead of using

<div style="{{style}}">...</div>

class

ng-class

<div ng-class="{{class}}">...</div>
<div class="{{class}}">...</div>

directives

create one directive per file. it's easy to mantain

use directives for manipulate dom

but it's difficult to test, so it's preferable to use alternative ways such as ngshow/nghide, css styles or nganimate

use lowercamelcase for naming

use short, unique and descriptive prefix. in the example we use smy-*. avoid ng-* and ui-* prefix

ex: smySalesCustomerInfo
html: <smy-sales-customer-info>

restrict to elements and attributes, avoid comments and classes

<div class="my-calendar-range"></div> // Avoid
// Recommended
<my-calendar-range></my-calendar-range> // Custom element
<div my-calendar-range></div> // Custom attribute

this will make your code more readable

don't forget to use           when you should deal with untrusted content

$sce

function ProductController($scope, $sce) {
    var vm = this;
    vm.title = $sce.trustAsHtml(vm.title.replace("\n", "<br/>"));
}

minification

use                       for gulp or grunt and comment functions that need automated dependency injection

will catch most dependencies, but it sometimes requires hints using the /* @ngInject */ syntax

angular
    .module('app')
    .controller('Avengers', Avengers);

/* @ngInject */
function Avengers(storage, avengerService) {
 ...
}
angular
    .module('app')
    .controller('Avengers', Avengers);

/* @ngInject */
function Avengers(storage, avengerService) {
 ...
}
Avengers.$inject = ['storage', 'avengerService'];

ng-annotate

services

encapsulate all the business logic in services

why business logic inside a controller is bad?

1. Controllers instantiated for each view and dies when the view unloads

2. Controllers are not reusable - they are coupled with the view

angular.module('Store')
.factory('Order', function () {
    var add = function (item) {
      this.items.push (item);
    };

    var remove = function (item) {
      if (this.items.indexOf(item) > -1) {
        this.items.splice(this.items.indexOf(item), 1);
      }
    };

    var total = function () {
      return this.items.reduce(function (memo, item) {
        return memo + (item.qty * item.price);
      }, 0);
    };

    return {
      items: [],
      addToOrder: add,
      removeFromOrder: remove,
      totalPrice: total
    };
});
//Order is used as a 'model'
angular.module('Store', [])
.controller('OrderCtrl', function (Order) {

  $scope.items = Order.items;

  $scope.addToOrder = function (item) {
    Order.addToOrder(item);
  };

  $scope.removeFromOrder = function (item) {
    Order.removeFromOrder(item);
  };

  $scope.totalPrice = function () {
    return Order.total();
  };
});

service

controller

others

do not use     prefix for the names of variables, properties and methods. This prefix is reserved for AngularJS usage

do not pollute your              . Only add functions and variables that are being used in the templates

$

$scope

use:

this will make your testing easier and prevent unexpected behavior

use promises (      ) instead of callbacks. It will make your code look more elegant and clean, and save you from callback hell

$q

$timeout

$interval

$window

$http

setTimeout

setInterval

window

$.ajax

instead of

instead of

instead of

instead of

don't use globals. use grunt-wrap or gulp-wrap for wrap your code in iife

When your code is minified and bundled into a single file for deployment to a production server, you could have collisions of variables and many global variables. An IIFE  protects you against both of these by providing variable scope for each file

why?

If planning to produce documentation, use jsDoc syntax

Use                          and                                to match your app structure

/**
 * Logger Factory
 * @namespace Factories
 */
(function() {
  angular
      .module('app')
      .factory('logger', logger);

  /**
   * @namespace Logger
   * @description Application wide logger
   * @memberOf Factories
   */
  function logger($log) {
      var service = {
         logError: logError
      };
      return service;

      ////////////

      /**
       * @name logError
       * @description Logs errors
       * @param {String} msg Message to log
       * @returns {String}
       * @memberOf Factories.Logger
       */
      function logError(msg) {
          var loggedMsg = 'Error: ' + msg;
          $log.error(loggedMsg);
          return loggedMsg;
      };
  }
})();

@namespace

@memberOf

Any code that needs to run when an application starts should be declared in a factory, exposed via a function, and injected into the run block

Code directly in a run block can be difficult to test.

why?

08

tips

my

start with a

hello world

tutorial

it's simple, easy to read and easy to follow

i recommend codecademy for start

i started with it, and i didn't finish the first module

but you should do!

if you come from another mvc framework, it will be easier

like django, flask ...

or ruby templating like eruby ...

remember dry rule:

don't repeat yourself

split in parts your html an import in the index

if you're going to use bootstrap templates, remember this rule

don't start learning best practices before learn angular syntax

really, don't do.

it's stupid. like start building a house without planes

or like make the filling without the cake

install angularjs plugin in sb3

it's made by angularUI

code completion.

snippets.

quick panel search.

and more.

use grunt to minify js and css and bower for dependencies

you will save a lot of time with bower

and save page load time because only download a CSS and one js

add                        to your code

use strict

to display the errors and scold the programmer

use

instead of

angular.js

angular

when you download with bower

because angular only downloads angular.js, since angular.js downloads all dependencies of angular (like ngroute, ngcookies...)

install angular batarang in your browser

batarang is made by google for extend the dev tools, adding tools for angular

you can view the models (scopes), performance and dependencies

you can identify fast an angular app looking at the url

http://angular-ui.github.io/angular-google-maps/#!/

you will see a hash before the route

this is not going to be true for all

09

conclusions

i think a lot about angular

angular is an incredible framework with a long road ahead

first

but it's not perfect

a lot of people think that angular will fail due to difficulty to learn compared to jquery

second

in my opinion

people who says that is focused in front development, and don't know any back language

getting started is easy if you come from any similar framework

like django

if i learned soon, anyone can learn fast

a lot of people think that angular is going to die with version 2

third

is angular dead?

what google says

in my opinion

angular is not going to die, not for now

but with angular 2, is a normal reaction move to another framework

like aurelia and durandal, which both will coexist

fourth

helpful creating readable, maintainable and extendable js apps

more elegant than jquery-like spaghetti code

10

credits

thanks to google by make an incredible framework and its documentation

thanks to flaticon for the delicious icons

thanks to google by respond all my questions

thanks to juan for teaching me, although I only understand the 20% of what you say

and of course, thanks to all by wasting your time listening my talk

credits for best practices

Copy of Angular 101

By Mohammed Amine EL JIRARI