Introducción a AngularJS
-
Upload
marcos-reynoso -
Category
Technology
-
view
1.254 -
download
2
description
Transcript of Introducción a AngularJS
Que es AngularJS ?
AngularJS es un framework javascript opensource
desarrollado por ingenieros de Google.
Un framework para crear aplicaciones web del lado del
cliente, ejecutándose con el conocido single-page
applications (aplicación de una sóla página) .
Extiende el tradicional HTML con etiquetas propias
(directivas)
Basado en MVC (Modelo-Vista-Controlador).
Hola Mundo con AngularJS
1. doctype html>
2. <html ng-app>
3. <head>
4. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.
js"></scrip>
5. </head>
6. <body>
7. <div>
8. <label>Name:</label>
9. <input type="text" ng-model="yourName" placeholder="Enter a name here">
10. <hr>
11. <h1>Hello {{yourName}}!</h1>
12. </div>
13. </body><!
14. </html>
Acerca del funcionamiento1. El browser carga el html y parsea este
dentro del DOM.2. El browser carga la libreria de
angular.js3. Angular espera por el evento
DOMContentLoaded.4. Angular busca la directiva ng-app, la
cual define el alcance de la aplicación.5. El módulo especificado en ng-app (si
hay alguno) es usado para configurar el $injector.
6. El $injector se utiliza para crear el servicio $compile, así como el $rootScope.
7. El servicio $compile es usado para compilar el DOM y linkearlo con el $rootScope.
Acerca del funcionamiento
Compiler: recorre el DOM y recoger todas las directivas. El resultado es una función linkeada.
Link: combinar las directivas con un Scope y produce un live view. Cualquier cambio en el modelo del Scope se reflejan en la vista, y cualquier interacción del usuario con la vista se reflejan en el modelo del Scope. Esto produce Two Way Data Binding
Data Binding
Controllers / Scope
<body ng-controller="SpicyCtrl"><button ng-click="chiliSpicy()">Chili</button><button ng-click="jalapenoSpicy()">Jalapeño</button><p>The food is {{spice}} spicy!</p></body> function SpicyCtrl($scope) {$scope.spice = 'very';$scope.chiliSpicy = function() { $scope.spice = 'chili';}$scope.jalapenoSpicy = function() { $scope.spice = 'jalapeño';}}
DirectivesExtienden HTML para estructurar la aplicación
● Declarativo● Usa la información que tiene en el Scope● Crea el DOM al vuelo.
<div><div ng-repeat=”user in users”>
<h3>{{user.name}}</h3><h3>{{user.descripcion}}</h3>
</div></div>
Este itera en una colección en el Scope y crea el DOM.
Custom Directives
app.directive('ngMyCustomDirective', function() {return {
restrict: 'A', template: '<div><h1>Esta es mi directiva</h1></div>' }});
Despues se puede usar :
<span ngMyCustomDirective></span>
restrict‘A' - <span ng-myD></span>'E' - <ng-myD></ng-myD>'C' - <span class="ng-myD"></span>'M’ - <!-- directive: ng-myD -->
Filters
Uso:
{{ expression | filter }}
{{ expression | filter1 | filter2 }}
Ejemplos:
4.678 | number:2
myArray | orderBy:'timestamp':true
Angularjs | uppercase
Custom Filters
<!doctype html>
<html ng-app="MyReverseModule">
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="Ctrl">
<input ng-model="greeting" type="greeting"><br>
No filter: {{greeting}}<br>
Reverse: {{greeting|reverse}}<br>
Reverse + uppercase: {{greeting|reverse:true}}<br>
</div>
</body>
</html>
angular.module('MyReverseModule', []).
filter('reverse', function() {
return function(input, uppercase) {
var out = "";
for (var i = 0; i < input.length; i++) {
out = input.charAt(i) + out;
}
// conditional based on optional argument
if (uppercase) {
out = out.toUpperCase();
}
return out;
}
});
function Ctrl($scope) {
$scope.greeting = 'hello';
}
index.html script.js
Servicesfunction myController($loc, $log) {
this.firstMethod = function() {
// use $location service
$loc.setHash();
};
this.secondMethod = function() {
// use $log service
$log.info('...');
};
}
// which services to inject ?
myController.$inject = ['$location', '$log'];
$http Service
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
$http Service
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Metodos
● $http.get
● $http.head
● $http.post
● $http.put
● $http.delete
● $http.jsonp
$resource Serviceangular.module('waWeatherService', [])
.factory('WeatherService', ['$resource', function ($resource) {
return $resource('http://api.openweathermap.org/data/2.5/:action', {}, { today: { method: 'JSONP', params: { action: 'weather', mode: 'json', units: 'metric', callback: 'JSON_CALLBACK' } } } ); }])
Custom Services
var app = angular.module('myApp', []); app.factory('testFactory', function(){ return { sayHello: function(text){ return "Factory says \"Hello " + text + "\""; }, sayGoodbye: function(text){ return "Factory says \"Goodbye " + text + "\""; } } });
function HelloCtrl($scope, testService, testFactory){ $scope.fromFactory = testFactory.sayHello("World");}
Service /Controller HTML
<div ng-controller="HelloCtrl"> <p>{{fromFactory}}</p></div>
Salida
Factory says "Hello World"
Routing
angular.module('phonecat', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/phones', {templateUrl: 'partials/phone-list.html', controller: PhoneListCtrl}).
when('/phones/:phoneId', {templateUrl: 'partials/phone-detail.html', controller:
PhoneDetailCtrl}).
otherwise({redirectTo: '/phones'});
}]);
Ejemplo SPI