Date post: | 10-May-2015 |
Category: |
Technology |
Upload: | marco-moscaritolo |
View: | 892 times |
Download: | 2 times |
Introduction to
HTML enhanced for web apps!
by / Marco Vito Moscaritolo @mavimo
<!-- directive: ng-mavimo -->{ { me.name } } -> Marco Vito Moscaritolo
{ { me.role } } -> Developer{ { me.company.name | link } } -> { { me.twitter | link } } ->
Agavee@mavimo
What's AngularJSAngularJS is a toolset for building the framework most suited to
your application development.
Heads UpStarting from directives...
...adding controllers......and filters...
...using routing......manage resources...
...and fun :)
DirectivesDirectives are a way to teach HTML new tricks. During DOM
compilation directives are matched against the HTML andexecuted. This allows directives to register behavior, or
transform the DOM.
The directives can be placed in element names, attributes,class names, as well as comments.
<span ng-repeat="exp"></span><span class="ng-repeat: exp;"></span><ng-repeat></ng-repeat><!-- directive: ng-repeat exp -->
<!doctype html><html ng-app> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js" </head> <body> <div> <input type="text" ng-model="sample" placeholder="Enter text"> <hr> <h1>{ { sample } }!</h1> </div> </body></html>
Write here...
<!doctype html><html ng-app> <head> <script src="js/angular.min.js" ></script> <script src="js/demo.js" ></script> </head> <body> <ul ng-controller="getGdgList"> <li ng-repeat="gdg in gdgs">{ {gdg.name} } have { {gdg.members} } members </ul> </body></html>
GDG Milan have 92 members
GDG Barcelona have 228 members
GDG Silicon Valley have 171 members
GDG Stockholm have 119 members
GDG Herzeliya have 140 members
GDG Ahmedabad have 78 members
GDG Lagos have 115 members
GDG Bangalore have 109 members
GDG Lima have 175 members
GDG L-Ab have 77 members
and alsong-showng-switchng-class...
Controllers<!doctype html><html ng-app> <head> <script src="js/angular.min.js" ></script> <script src="js/demo.js" ></script> </head> <body> <ul ng-controller="getTweets"> <li ng-repeat="tweet in tweets"></li> </ul> </body></html>
function getTweets($scope, $http) { var search = 'gdg'; var url = 'http://search.twitter.com/search.json?q=' + search;
$http({ method: 'GET', url: url }) .success(function(data, status, headers, config) { $scope.tweets = data.results; }) .error(function(data, status, headers, config) { console.log('Error: fetch tweets'); $scope.tweets = {}; });
return $scope;}
Methods in controllerfunction getTweets($scope, $http) { // ...
$scope.getMore = function () { // ... } // ... return $scope;}]);
<ul ng-controller="getTweets"> <li ng-repeat="tweet in tweets"></li> <li ng-click="getMore()">Get more</li></ul>
Controller in modulevar gdgApp = angular.module('gdgApp', []);
gdgApp.controller('getTweets', ['$scope', '$http', function($scope, $http) { var search = 'gdg'; var url = 'http://search.twitter.com/search.json?q=' + search;
$http({ method: 'GET', url: url }). success(function(data, status, headers, config) { $scope.tweets = data.results; }). error(function(data, status, headers, config) { console.log('Error: fetch tweets'); $scope.tweets = {}; });
return $scope;}]);
Dependency Injection(also know as Inversion of Control)
Dependency Injection (DI) is a software design pattern thatdeals with how code gets hold of its dependencies.
ServicesAngular services are singletons that carry out specific tasks.
Eg. $http service that provides low level access to the
browser's XMLHttpRequest object.
gdgApp.controller('getTweets', ['$scope', '$http', function($scope, $http) { // ... return $scope;}]);
angular.module('gdgModuleAlarm', []). factory('alarm', function($window) { return { alarm: function(text) { $window.alert(text); } }; });
Injectors// New injector created from the previus declared module.var injector = angular.injector(['gdgModuleAlarm', 'ng']);
// Request any dependency from the injectorvar a = injector.get('alarm');
// We can also force injecting usingvar alarmFactory = function (my$window) {};alarmFactory.$inject = ['$window'];
FiltersFilters perform data transformation.
They follow the spirit of UNIX filters and use similar syntax |(pipe).
<!doctype html><html ng-app> <head> <script src="js/angular.min.js" ></script> <script src="js/demo.js" ></script> </head> <body> <a href="" ng-click="predicate = 'members'; reverse=!reverse"<Sort</a> <ul ng-controller="getGdgList"> <li ng-repeat="gdg in gdgs | orderBy:predicate:reverse "> have members </ul> </body></html>
GDG MILAN have 92 membersGDG BARCELONA have 228 membersGDG SILICON VALLEY have 171 membersGDG STOCKHOLM have 119 membersGDG HERZELIYA have 140 membersGDG AHMEDABAD have 78 membersGDG LAGOS have 115 membersGDG BANGALORE have 109 membersGDG LIMA have 175 membersGDG L-AB have 77 members
Sort
Creating custom filtersangular.module('agaveeApp', []) .filter('orderByVersion', function() { return function(modules, version) { var parseVersionString = function (str) { /* .. */ }; var vMinMet = function(vmin, vcurrent) { /* .. */ }; var result = [];
for (var i = 0; i < modules.length; i++) { if (vMinMet(modules[i].version_added, version)) { result[result.length] = modules[i]; } }
return result; };});
ModelThe model is the data which is merged with the template to produce the view.
<!doctype html><html ng-app> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js" </head> <body> <div> <input type="text" ng-model="sample" placeholder="Enter text"> <hr> <h1>!</h1> </div> </body></html>
Configurationangular.module('gdgApp', []) .constant('gdg', { 'url' : 'http://localhost:3000', 'token': 'e9adf82fd1cb716548ef1d4621a5935dcf869817' })
// Configure $http .config(['$httpProvider', 'gdg', function ($httpProvider, gdg) { $httpProvider.defaults.headers.common['X-gdg-API-Key'] = gdg.token; } ]);
Routingangular.module('gdgApp', []) // Configure services .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/projects', { templateUrl: 'views/projects.html', controller: 'ProjectsCtrl' });
$routeProvider.when('/projects/:project', { templateUrl: 'views/project.html', controller: 'ProjectCtrl' });
$routeProvider.otherwise({redirectTo: '/projects'}); }]);
Resourceangular.module('resources.project', ['ngResource'])
.factory('Project', ['$http', '$resource', 'gdg', function ($http, gdg) {
return $resource(gdg.url + '/project/:projectId', {projectId:'@id'}, {
query : { method : 'GET', isArray:true},
create : { method : 'POST' },
save : { method : 'PUT' },
delete : { method : 'DELETE' }
});
}]);
// ...
var p = new Project();
p.name = 'GDG Milan';
p.$save();
angular.module('resources.project', ['ngResource']) .factory('Project', ['$http', 'gdg', function ($http, gdg) { var Project = function (data) { angular.extend(this, data); };
// a static method to retrieve Project by ID Project.get = function (id) { return $http.get(gdg.url + '/projects/' + id).then(function (response) { return new Project(response.data); }); };
// an instance method to create a new Project Project.prototype.create = function () { var project = this; return $http.post(gdg.url + '/projects.json', project).then(function (response) project.id = response.data.id;
TestingKarma - a test runner that fits all our needs.
Jasmine - Jasmine is a behavior-driven developmentframework for testing JavaScript code.
describe('Controller: getGdgList', function () {
// load the controller's module beforeEach(module('gdgApp'));
var getGdgList, scope;
// Initialize the controller and a mock scope beforeEach(inject(function ($controller) { scope = {}; getGdgList = $controller('getGdgList', { $scope: scope }); }));
it('GDG List must display defined number of items', function () { expect(scope.gdgs.length).toBe(10); });
Angular 1.2...is coming!
More modularIntroduce ng-animate (and related)Support to mobile (÷/-)
Demo
?Questions time
THE ENDMarco Vito Moscaritolo / @mavimo