Documente Academic
Documente Profesional
Documente Cultură
Juanda
Abril 2015
2
Contents
1 Introduccin 7
1.1 Qu es AngularJS . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.2 Entorno de trabajo . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3 Servidor web: nodejs . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4 Servidor web: python . . . . . . . . . . . . . . . . . . . . . . . . 8
1.5 Libreras de AngularJS . . . . . . . . . . . . . . . . . . . . . . . . 9
1.6 Libreras extra de AngularJS . . . . . . . . . . . . . . . . . . . . 9
3
4 CONTENTS
3 Mi primera aplicacin 19
3.1 Crear un boilerplate . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.2 Prueba del boilerplate . . . . . . . . . . . . . . . . . . . . . . . . 19
3.3 Anlisis de la estructura . . . . . . . . . . . . . . . . . . . . . . . 20
3.4 ng-app . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.5 Limitar nuestra aplicacin angular . . . . . . . . . . . . . . . . . 20
3.6 Directivas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.7 Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.8 Aplicacin Hola Mundo . . . . . . . . . . . . . . . . . . . . . . . 22
3.9 Controller Hola Mundo . . . . . . . . . . . . . . . . . . . . . . . 22
3.10 Aplicacin: sintaxis nueva . . . . . . . . . . . . . . . . . . . . . . 23
3.11 Sintaxis js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.12 Built-in directives . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.13 Hola Mundo con ng-click . . . . . . . . . . . . . . . . . . . . . . . 24
3.14 Hola Mundo con ng-click: js . . . . . . . . . . . . . . . . . . . . . 24
4 Formularios 27
4.1 Validacin de formularios . . . . . . . . . . . . . . . . . . . . . . 27
4.2 Requerimientos ejemplo . . . . . . . . . . . . . . . . . . . . . . . 27
4.3 Cdigo base . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.4 Deshabilitar botn de envo . . . . . . . . . . . . . . . . . . . . . 29
4.5 Mensajes de ayuda . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.6 Estilos mediante las clases de Angular . . . . . . . . . . . . . . . 29
4.7 Clase condicional ng-class . . . . . . . . . . . . . . . . . . . . . . 30
4.8 Eventos para formularios . . . . . . . . . . . . . . . . . . . . . . . 30
5 Filters 31
5.1 Para qu sirven? . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.2 Sintaxis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.3 Ejemplo de uso de filtros: . . . . . . . . . . . . . . . . . . . . . . 32
5.4 Localizacin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
CONTENTS 5
6 Servicios 33
6.1 Qu es un servicio? . . . . . . . . . . . . . . . . . . . . . . . . . 33
6.2 Dependency Injection . . . . . . . . . . . . . . . . . . . . . . . . 34
6.3 $http service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.4 $http va get . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
7 Vistas y Rutas 37
7.1 Includes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
7.2 ng-include . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
7.3 ng-view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
7.4 Librera ngRoute . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
7.5 Incluir ngRoute en nuestra aplicacin . . . . . . . . . . . . . . . . 38
7.6 Como usar $routeProvider . . . . . . . . . . . . . . . . . . . . . . 39
7.7 Rutas con parmetros . . . . . . . . . . . . . . . . . . . . . . . . 39
7.8 Rutas ms avanzadas . . . . . . . . . . . . . . . . . . . . . . . . . 40
8 Custom Directives 41
8.1 Componentes en html . . . . . . . . . . . . . . . . . . . . . . . . 41
8.2 Concepto de Custom Directives . . . . . . . . . . . . . . . . . . . 42
8.3 Construir una Custom Directive . . . . . . . . . . . . . . . . . . 42
8.4 Por qu usar directivas . . . . . . . . . . . . . . . . . . . . . . . . 43
8.5 Custom directive como include . . . . . . . . . . . . . . . . . . . 43
6 CONTENTS
Chapter 1
Introduccin
1.1 Qu es AngularJS
Es la librera ms utilizada de JavaScript.
Est mantenida por Google
Uno de los frameworks ms usados (tanto en cliente como servidor) en la
actualidad.
Muy adecuado para el desarrollo de un SPA (Single Page Application)
7
8 CHAPTER 1. INTRODUCCIN
node server.js
http://localhost:5000
Arquitectura de una
aplicacin Angular
Modelo
Vista
Whatever
11
12 CHAPTER 2. ARQUITECTURA DE UNA APLICACIN ANGULAR
Controlador:
Reutilizar componentes
Alguna desventaja:
Desarrolladores de frontend
Desarrolladores de backend
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></s
<script>
$(document).ready(function() {
var $nombre = $(#nombre);
$nombre.keyup(function() {
$(#saludo).text(Hola + $nombre.val() + !);
});
});
2.9. EJEMPLO EN ANGULARJS MEDIANTE DATABINDING 15
</script>
</head>
<body>
<input id="nombre" type="text">
<h2 id="saludo"></h2>
</body>
</html>
<!doctype html>
<html ng-app>
<head>
<meta charset="UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
</head>
<body>
<input type="text" ng-model="nombre">
<h2>Hola {{nombre} }</h2>
</body>
</html>
2.10 Controlador
En el cdigo anterior se puede echar de menos un controller:
2.12 Modules
Los modules son las partes lgicas en las que puedes dividir tu aplicacin
<div ng-controller="FutbolistasController">
<h2>Lista de futbolistas</h2>
<ul>
<li ng-repeat="futbolista in Futbolistas">
{ {futbolista.nombre}} {{futbolista.apellido} } juega en el { {futbolista.e
</li>
</ul>
</div>
Chapter 3
Mi primera aplicacin
<!DOCTYPE html>
<html lang="es" ng-app="">
<head>
<meta charset="UTF-8">
<title>Mi primera aplicacin</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
</head>
<body>
<p>Si a continuacin ves un 7 en el navegador, tienes todo bien configurado :-) </p>
<p>{{5+2}}</p>
</body>
</html>
node server.js
19
20 CHAPTER 3. MI PRIMERA APLICACIN
Un atributo ng-app
Una expresin que AngularJS calcula
Observa que si ponemos el script de angularJS al final del body, se llega a ver la
expresin antes de su evaluacin.
El documento no es vlido segn la W3C
3.4 ng-app
ng-app es una directiva de angular
Tambin es un atributo html, pero desconocido:
Indica que lo que hay dentro de sus etiquetas es cdigo de una aplicacin
Angular
Si no lo ponemos la expresin no se evaluar
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
3.6. DIRECTIVAS 21
3.6 Directivas
Las directivas en AngularJS son nuevos atributos o etiquetas HTML que
extienden el documento html
La directiva ng-app inicializa una aplicacin AngularJS
Hay muchas ms, AngularJS extiende HTML a travs de sus directivas
<!DOCTYPE html>
<html lang="es" ng-app="">
<head>
<meta charset="UTF-8">
<title>Mi primera aplicacin</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
</head>
<body>
<p ng-init="numero=5">{{numero+2}}</p>
</body>
</html>
3.7 Controllers
Un controller se asocia a un mdulo determinado
Se escriben con el sufijo Controller
Es el sitio donde definimos cas toda la lgica de nuestra aplicacin
22 CHAPTER 3. MI PRIMERA APLICACIN
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Saludar</title>
</head>
<body ng-app="saludar">
<div ng-controller="mensajesController">
<p>{{saludo}}</p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></scri
<script src="saludar.js"></script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Saludar</title>
</head>
<body ng-app="saludar">
<div ng-controller="mensajesController as mensajes">
<p>{{mensajes.saludo}}</p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
<script src="saludar2.js"></script>
</body>
</html>
3.11 Sintaxis js
Asociamos la variable al controlador por medio de this
Podemos acceder directamente desde el controlador (sin usar $scope)
Funciona desde la versin 1.3 de Angular
ng-show
24 CHAPTER 3. MI PRIMERA APLICACIN
ng-hide
ng-repeat
ng-click
etc.
Nos puede ayudar utilizar alguna directiva de las anteriores, por ejemplo
ng-click.
<!doctype html>
<html ng-app="holaMundoApp">
<head>
<meta charset="UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></scri
<script src="holamundo.js"></script>
</head>
<body>
<div ng-controller="holaMundoController">
<input type="text" ng-model="nombre">
<h2 ng-click="saludar()">Hola {{nombre}}</h2>
</div>
</body>
</html>
Formularios
Formulario:
27
28 CHAPTER 4. FORMULARIOS
nombre es requerido
<head>
<meta charset="UTF-8">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="s
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></scri
<script src="formulario.js"></script>
</head>
</html>
Podemos usar las clases que Angular inyecta de forma dinmica para generar
estilos:
.ng-valid { }
.ng-invalid { }
.ng-pristine { }
.ng-dirty { }
.ng-invalid-required { }
.ng-invalid-minlength { }
.ng-valid-max-length { }
30 CHAPTER 4. FORMULARIOS
ng-click
ng-dbl-click
ng-mousedown
ng-mouseup
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
ng-keydown
ng-keyup
ng-keypress
ng-change
Chapter 5
Filters
5.2 Sintaxis
En las templates de vistas se utilizan mediante una tubera:
{{ expression | filter }}
{{ expression | filter:argument1:argument2:... }}
31
32 CHAPTER 5. FILTERS
5.4 Localizacin
La salida del filtro siguiente ser 1,234.00
{{ 1234 | number:2 }}
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/i18n/angular-locale_es-es.
Chapter 6
Servicios
6.1 Qu es un servicio?
La funcin se externaliza
Ejemplos de servicios:
$http
$route
$window
$location
33
34 CHAPTER 6. SERVICIOS
Va XMLHttpRequest
Va JSONP
$http.head
$http.put
$http.delete
$http.jsonp
$http.patch
36 CHAPTER 6. SERVICIOS
Chapter 7
Vistas y Rutas
7.1 Includes
html no soporta incluir una pgina html dentro de otra:
7.2 ng-include
En Angular podemos hacer includes mediante la directiva ng-include
Angular espera una variable. Por eso datosclientes.html va entre comillas simples:
7.3 ng-view
ng-include a veces no es suficiente (ni necesario siquiera)
ng-view es totalmente necesario para un SPA
37
38 CHAPTER 7. VISTAS Y RUTAS
<div ng-app="mainApp">
...
<div ng-view></div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-route.js"></script
.when(path, route);
.otherwise(params);
angular.module(MainApp)
.config([$routeProvider,
function($routeProvider) {
$routeProvider.
when(/addStudent, {
templateUrl: addStudent.htm,
controller: AddStudentController
}).
when(/viewStudents, {
templateUrl: viewStudents.htm,
controller: ViewStudentsController
}).
otherwise({
redirectTo: /addStudent
});
}]);
http://www.miapp.com/#/viewStudents/<id>
.when (/viewStudents/:id, {
.....
});
Podramos pasar tambin varios parmetros (nombre y apellidos) y parmetros opcionales (mote):
.controller(ViewStudentsController, function($routeParams) {
var self = this;
self.estudiante = $routeParams.nombre + " " + $routeParams.apellido;
});
http://www.miapp.com/#/addStudent
http://www.miapp.com/#/viewStudents
vistas anidadas
urls generadas de forma dinmica
Custom Directives
$(document).ready(function() {
$(#example).DataTable();
} );
$(input[type=text]).datePicker()
41
42 CHAPTER 8. CUSTOM DIRECTIVES
<data-table></data-table>
<date-picker></date-picker>
A: atributo
E: elemento
C: clase
app.directive(HolaMundo, function() {
return {
restrict: AE,
replace: true,
template: <h3>Hola Mundo!</h3>
};
});
8.4. POR QU USAR DIRECTIVAS 43
<hola:mundo></hola:mundo>
<hola-mundo></hola-mundo>
<div hola:mundo></div>
<div hola-mundo></div>
<aside class="col-sm-3">
<libro-portada></libro-portada>
<h4><libro-valoracion></libro-valoracion></h4>
</aside>
<div class="col-sm-9">
<h4><libro-titulo></libro-titulo></h4>
<libro-autor></libro-autor>
<libro-genero></libro-genero>
....
</div>
app.directive(HolaMundo, function() {
return {
restrict: AE,
replace: true,
templateUrl: holamundo.html
};
});