From Zero to Angular in one session
<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>
var app = angular.module("helloApp", []);
app.controller("HelloCtrl", function($scope) {
$scope.name = "";
});
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>
<!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>
<form>
¿Cómo te llamas? <input type="text" id="nombre">
</form>
<form>
¿Cómo te llamas? <input type="text" ng-model="nombre">
</form>
<script>
$(function(){
var campoTexto = $("#nombre");
var titular = $("h1");
campoTexto.on("keyup", function(){
titular.text("Hola " + campoTexto.val());
});
});
</script>
<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>
<div id="app" ng-app>
<div id="app" ng-app='myApp'>
<button ng-click="runWhenButtonClicked()"></button>
<div ng-click="runWhenDivClicked()"></div>
<h3>Double the count is: {{ 2 * count }}</h3>
<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>
angular.module('myApp', []);
angular.module('myApp');
.controller('otroCtrl', function($scope){
$scope.algo = "probando scope...";
$scope.miDato = "otra cosa..."
});
<p>{{ algo }}</p>
<input type="text" ng-model="miDato">
angular.module('myApp')
.controller('HomeController', function($scope) {
$scope.name = 'Cory';
});
<div ng-controller='HomeController'>
<p>{{name}}</p>
</div>
// 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
);
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;
}]);
.
├── 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
angular.module('demo', []);
angular.module('demo.module', []);
angular.module('demo.routes', []);
angular.module('demo', [
// App module
'demo.modules'
]);
angular.module('demo.module', [
// App routes
'demo.routes'
]);
angular.module('demo.routes', [
// Angular routes
'ngRoute'
]);
<body ng-app="demo"></body>
<body ng-app="demo">
<div ng-include="'/app/partials/sidebar.partial.html'"></div>
<div ng-include="'/app/partials/footer.partial.html'"></div>
</body>
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: '/'
});
}]);
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "/app/partials/home.partial.html"
})
.otherwise({
redirectTo: '/'
});
<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>
angular
.module('demo.controller.social', [])
.controller('SocialController', SocialController);
SocialController.$inject = ['$scope'];
function SocialController($scope, request){
}
function SocialController($scope, request){
$scope.data = [
{title: 'Twitter'},
{title: 'Google+'},
{title: 'Facebook'}
];
}
angular
.module('demo.controller.post', [])
.controller('PostController', PostController);
PostController.$inject = ['$scope'];
function PostController($scope){
}
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
<md-social></md-social>
<div md-social></div>
angular
.module('demo.factory.request', [])
.factory('requestFactory', requestFactory);
requestFactory.$inject = ['$http'];
function requestFactory($http) {
}
angular
.module('demo.factory.request', [])
.factory('requestFactory', requestFactory);
requestFactory.$inject = ['$http'];
function requestFactory($http) {
function get() {
};
}
angular
.module('demo.factory.request', [])
.factory('requestFactory', requestFactory);
requestFactory.$inject = ['$http'];
function requestFactory($http) {
function get(url, success) {
};
}
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
};
}
$http({
url: '...',
method: 'GET'
});
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;
});
}
<div class="row" ng-controller="PostController">
<h3>{{post.title}}</h3>
.
├── 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
ex: smyland.product
b
a
a.b
/* avoid */
var app = angular.module('app', ['ngAnimate']);
app.controller('SomeController', SomeController);
function SomeController() { }
/* recommended */
angular
.module('app', ['ngAnimate'])
.controller('SomeController', SomeController);
function SomeController() { }
ex: ProductController
// Don't do this
module.controller('MyCtrl', function ( ... ) {
// ...
}
// Do this
module.controller('MyCtrl', MyCtrl);
function MyCtrl( ... ) {
// ...
}
// Solution - Explicit inject dependencies
module.controller('MainController', MainController);
function MainController($scope) {
// ...
};
MainController.$inject = ['$scope'];
<!-- avoid -->
<div ng-controller="Customer">
{{ name }}
</div>
<!-- recommended -->
<div ng-controller="Customer as customer">
{{ customer.name }}
</div>
controllerAs
controllerAs
this
function Customer($scope) {
$scope.name = {};
$scope.sendMessage = function() { };
}
function Customer() {
this.name = {};
this.sendMessage = function() { };
}
controllerAs
this
function Customer() {
this.name = {};
this.sendMessage = function() { };
}
function Customer() {
var vm = this;
vm.name = {};
vm.sendMessage = function() { };
}
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() {/* */}
}
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>
function MyCtrl(s) {
// ...
}
module.controller('MyCtrl', ['$scope', MyCtrl]);
function MyCtrl($scope) {
// ...
}
module.controller('MyCtrl', ['$scope', MyCtrl]);
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);
};
});
ng-bind
ng-cloak
{{ }}
$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}}">
<div style="{{style}}">...</div>
class
ng-class
<div ng-class="{{class}}">...</div>
<div class="{{class}}">...</div>
ex: smySalesCustomerInfo
html: <smy-sales-customer-info>
<div class="my-calendar-range"></div> // Avoid
// Recommended
<my-calendar-range></my-calendar-range> // Custom element
<div my-calendar-range></div> // Custom attribute
$sce
function ProductController($scope, $sce) {
var vm = this;
vm.title = $sce.trustAsHtml(vm.title.replace("\n", "<br/>"));
}
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
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();
};
});
$
$scope
$q
$timeout
$interval
$window
$http
setTimeout
setInterval
window
$.ajax
/**
* 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
http://angular-ui.github.io/angular-google-maps/#!/