https://slides.com/uesteibar/angularjs-workshop/live
by Unai Esteibar
¿Qué es AngularJS?
- Framework MCV para Web-Apps en HTML5
- Open Source (@github, Licencia MIT)
- Fundado y respaldado por Google
Arquitectura Cliente-Servidor
Web 2.0
Server
Cliente
Lógica de negocio
DDBB
Renderizado HTML
JS básico
HTML
Arquitectura Cliente-Servidor
Web Apps en la actualidad
Server
Lógica de negocio
DDBB
RESTful
Lógica de negocio
JS + JQuery, AngularJS...
HTML
JSON
¿por qué angularjs?
Traslado de parte de la lógica de negocio al cliente
Patrones de diseño: MVC, Singleton...
SPA + JSON = Menor carga de transferencia = Mejor rendimiento
Código mejor estructurado
Hacer más con menos código
Powered by Google
Comunidad
ANGULARJS VS REGULAR JS
HTML + JS
<ul id="myList">Lista:</ul>var datos = ["dato 1", "dato 2", "dato 3"];
var lista = "";
var i = 0;
for (i = 0; i < datos.length; i++) {
lista += "<li>" + datos[i] + "</li>";
}
document.getElementById('myList').innerHTML = lista;HTML + angularJS
<ul>
<li ng-repeat="dato in datos">{{dato}}</li>
</ul>var datos = ["dato 1", "dato 2", "dato 3"];¿y por qué no angularjs?
Rendimiento frente a nativo (Mobile, Desktop...)
SEO
Posibilidades
AngularJS + HTML5 = Web Apps
AngularJS + Cordova / Phonegap = Mobile Apps
AngularJS + Node-Webkit = Desktop Apps
MVC
-
Modelo: Factory, Scope
-
Vista: HTML, Directivas, Filtros
- Controlador
eSTRUCTURA DE ANGULAR
HTML
DIRECTIVAS
VISTAS
FILTROS
JS
FACTORY
CTRL
CONFIG
SERVICE
NO DOM!
$SCOPE
Comunicador
Estructura de ficheros
- 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
- js
- package.json
Carpetas
JS
CSS
HTML
Otros
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>Mi 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>HOLA, SOY LA VISTA 1</h1>VIEW2.html
<h1>HOLA, SOY LA VISTA 2</h1>controllers.js
myApp.controller('View1Ctrl', ['$scope',
function ($scope) {
}]);
myApp.controller('View2Ctrl', ['$scope',
function ($scope) {
}]);VAMOS A VERLO
directivas
ng-model
<input type="text" ng-model="texto">
<p>{{texto}}</p>- Crea una variable
- Doble bindado
- Accesible desde $scope
myApp.controller('View1Ctrl', ['$scope',
function ($scope) {
}]);Vista 1
Vamos a verlo
<input type="text" ng-model="texto">
<button ng-click="hola()">DI HOLA</button>myApp.controller('View2Ctrl', ['$scope',
function ($scope) {
$scope.hola = function(){
alert($scope.texto);
};
}]);Vista 2
Vamos a verlo
ng-CLICK
Ejecuta una función declarada en $scope cuando se hace click
ng-repeat
Repite un componente HTML dependiendo de un array
<ul>
<li ng-repeat="dato in datos">{{dato}}</li>
</ul>myApp.controller('View1Ctrl', ['$scope',
function ($scope) {
$scope.datos = ["dato 1", "dato 2", "dato 3", "dato 4"];
}]);Posibilidades añadidas: aplicar filtros, ordenar...
Otras directivas
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) {
}]);Declaración
myApp.controller('HomeCtrl', ['$scope',
function ($scope) {
// SET
$scope.texto = "Hola";
// GET
var texto = $scope.texto;
}]);$scope
<input type="text" ng-model="texto">myApp.controller('HomeCtrl', ['$scope',
function ($scope) {
$scope.texto = "Hola";
}]);Controllers anidados
<div ng=controller="HomeCtrl">
<div ng=controller="InputCtrl">
<p>{{texto}}</p>
</div>
</div>myApp.controller('InputCtrl', ['$scope',
function ($scope) {
$scope.texto = "Hola";
}]);myApp.controller('HomeCtrl', ['$scope',
function ($scope) {
$window.alert("Hola");
}]);Inyección de dependencias
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");
}]);Services & factories
Services & factories
Wrapper de lógica de negocio (http requests, acceso a bases de datos locales, datos default...).
Nos permiten reutilizar código en distintos controllers a lo largo de la aplicación (validación de datos, acceder a SessionStorage para token de auth...).
Service: Instancia un nuevo objecto.
Factory: Siempre devuelve una referencia al mismo objeto.
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) {
return data;
});
};
$scope.githubUser = getGithubUser('uesteibar');
$scope.dbVersion = AppInfo.getDBVersion();
}]);Los inyectamos
Ejercicio
Crear una aplicación de tareas donde pueda:
- Cargar una lista de tareas default
- Crear una tarea
- Eliminar una tarea
- Filtrar las tareas
¿Y AHORA QUÉ?
- Route con parámetros
- http CRUDs (Servicios)
- módulos externos
- Storage (Local, Session, ng-cache...)
- Directivas propias
Recursos:
Docs del taller
Presentación: https://slides.com/uesteibar/angularjs-workshop
Ejercicios y ejemplos: https://github.com/uesteibarworkshops
AngularJS-Workshop
By uesteibar
AngularJS-Workshop
- 1,626



