You are on page 1of 4

ng-show shows or hides the given HTML element based

AngularJS on the expression provided. In example, isShown is a


model in bound controller.
<p ng-show="isShown">Yes!</p>
HTML enhanced for web apps!
ng-click allows you to specify custom behavior when
an element is clicked. In example, recompute() is a
MVC method in bound controller.
Model View Controller <button ng-click='recompute()'>=</button>
Controller
ng-change evaluates the given expression when the
Controller is defined at root scope. user changes the input (evaluated immediately, not at
<!-- Concepts of MVC --> the end of a change)
<html ng-app>
<input ng-model='a' ng-change='recompute()'/>
<head>
<script src="angular.js"></script>
$watch
</head>
<body> Call $watch() with an expression to observe and a callback
<div ng-controller='HelloController'> that gets invoked whenever that expression changes. The
<p>Hello {{target}}</p> last parameter true tells deep inspection.
</div> $scope.data = {a: 0, b:0};
</body> ...
<script type="text/javascript"> $scope.$watch('data', $scope.recompute, true);
function HelloController($scope){
$scope.target = 'world' Form Validation
}
</script> <form name="addFruitForm">
</html> <div>Name: <input ng-model='fruit.name' required
ng-minlength='3'></div>
ng-controller => Bind angular controller to given <div>
template Amount: <input type='number' min='1' max='10'
ng-model='fruit.amount' name='amount' required>
Angular expressions enclosed in curly braces {{ }}
<span class="label label-warning"
Two-way Data Binding ng-show='!addFruitForm.amount.$valid'>
Use ng-model directive to create a two way data-binding 1-10
</span>
between the input element and the target model.
</div>
Template <div><button ng-disabled='!addFruitForm.$valid'
<div ng-controller='HelloController'> ng-click='addFruit()'>Add</button></div>
<input ng-model='target'> </form>
<p>Hello {{target}}</p>
</div> Filters
{{7/3 | number}}
Script {{7/3 | number:1}}
function HelloController($scope){ {{12000 | currency:'THB'}}
$scope.target = 'world' ... ng-repeat="f in fruits | orderBy:'amount'" ...
}

Modules
Useful Features The process is more declarative which is easier to
understand
Directives
In unit-testing there is no need to load all modules,
ng-repeat instantiates a template once per item from a which may aid in writing unit-tests.
collection. It provides $index for index of the collection Additional modules can be loaded in scenario tests,
and $first, $middle, $last as Boolean. which can override some of the configuration and help
Template end-to-end test the application
<ul ng-controller='ListController'> Third party code can be packaged as reusable
<li ng-repeat='fruit in fruits'> modules.
{{fruit.name}} = {{fruit.amount}} The modules can be loaded in any/parallel order (due
</li> to delayed nature of module execution).
</ul> var myApp = angular.module('myApp', [])
myApp.controller('Ctrl', function ($scope){
Script $scope.target = 'world'
function ListController($scope){ });
$scope.fruits = [{name: 'mango', amount: 2},
{name: 'banana', amount: 5}, Template must specify name of target module.
{name: 'orange', amount: 4}]; <html ng-app="myApp">
} ...
</html>
ng-class dynamically set CSS classes on an HTML
element
<tr ng-repeat='fruit in fruits'
ng-class='{highlight: $first}'>

PUPA & CNR, COE/PSU - V1.08 1


Module Loading Install node modules by running following
Modules can list other modules as their dependencies. commands at project directory
Note: include ui-bootstrap.js and bootstrap.css >> npm install
Template
<div> Install MongoDB driver
Focus me: <input tooltip-trigger="focus" Note: you might need --msvs_version option in
tooltip-placement="right" tooltip="See?"/> Windows 8
</div> >> npm install mongodb --msvs_version=2013

Script Create server.js to provide RESTful server, run it.


var myApp = angular.module('myApp', >> node server.js
['ui.bootstrap']);

Dependencies Injection Communicate with Server


The simplest way to get hold of the dependencies, is to
assume that the function parameter names are the names $http
of the dependencies. A core Angular service that facilitates communication with
the remote HTTP servers
myApp.controller('Ctrl', function($scope, $http){
$http.get('/books').success(function(data) { $http.get('/books').
$scope.books = data; success(function(data) {
}); $scope.books = data;
}); });
});
Custom Filters
Just register a new filter factory function with your module. ngResource
Provide interaction support with RESTful services via the
myApp.filter('withSign', function(){
var filter = function(input){ $resource service.
if(input > 0) Note: include angular-resource.js in your code.
return "+" + input; var myApp = angular.module('myApp', ['ngResource']);
else myApp.factory('Book', function($resource){
return "" + input; return $resource('books/:_id', {_id: '@_id'});
}; });
return filter; myApp.controller('Ctrl', function($scope, Book){
}); $scope.books = Book.query();
});

Services Default Actions


There are three functions for creating generic services, with { 'get': {method:'GET'},
different levels of complexity and ability. 'save': {method:'POST'},
[provider | factory | service] 'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
myApp.factory('Book', function(){ 'delete': {method:'DELETE'} };
var book = {};
book.query = function(){
Promise
return [
{title: 'AngularJS', price: 500}, An interface for interacting with an object that represents
{title: 'CSS', price: 300}, the result of an action that is performed asynchronously,
{title: 'Bootstrap', price: 320} and may or may not be finished at any given point in time.
]; Note: you can chain then.
}; promise.then(function(greeting) {
return book; alert('Success: ' + greeting);
}); }, function(reason) {
myApp.controller('BookCtrl', function($scope, Book){ alert('Failed: ' + reason);
$scope.books = Book.query(); }, function(update) {
}); alert('Got notification: ' + update);
});

MEAN Stacks
MongoDB, Express, Angular, Node Unit Testing
Install & Run MongoDB With great power comes great responsibility.
>> mongod --dbpath=data/ Karma
Install karma globally so we can run unit-testing from
Install Node (npm is also installed)
command line.
Create project directory with package.json in it
>> npm install g karma
{
"name": "angularjs-seed",
"description": "A starter project for AngularJS", Create karma configuration files by running this command
"dependencies": { at project directories.
"express": "3.x" >> karma init
},
"devDependencies": { ... }
}

PUPA & CNR, COE/PSU - V1.08 2


Answer the questions accordingly. Then create test
specifications in Jasmine syntax. Bootstrap
describe('unit-test', function() { Accordion
it('should work', function(){
The accordion directive builds on top of the collapse
expect(true).toBe(true);
}); directive to provide a list of items
}); Template
<label class="checkbox">
Run the test. <input type="checkbox" ng-model="oneAtATime">
>> karma start karma.conf.js Open only one at a time
</label>
Test services and controllers <accordion close-others="oneAtATime">
<accordion-group heading="{{group.title}}"
describe("myModule", function() { ng-repeat="group in groups" is-open="true">
var service; {{group.content}}
var scope; </accordion-group>
</accordion>
beforeEach(function(){
module('myModule');
Script
inject(function($controller, myService){
scope = {}; myApp.controller('Ctrl', function($scope){
$controller('myController', {$scope: scope}) $scope.groups = [
service = myService; {title: "Nexus S", content: "Fast."},
}); {title: "MOTOROLA", content: "The Next."}
}); ];
});
it("should know how to calculate", function() {
expect(service.plus(2, 3)).toBe(5); close-others to control whether expending an
}); item will cause the other items to close.
heading title of heading.
it("should initialize lastResult", function() {
expect(scope.lastResult).toBe(0); Alert
}); Directive to generate alerts from the dynamic model data.
});
Template
<alert ng-repeat="alert in alerts" type="alert.type"
Routes close="closeAlert($index)">
{{alert.msg}}
Though AJAX apps are technically single-page apps (in the </alert>
sense that they only load an HTML page on the first request, <form class="form-inline">
and then just update areas within the DOM thereafter), we <div class="form-group">
usually have multiple sub-page views. <input class="form-control" type="text"
Note: include angular-route.js in your code. ng-model="message">
</div>
Template <button class="btn" ng-click="addAlert()">
<body> Click
<div ng-view> </button>
</div> </form>
</body>
<script type="text/javascript"> Script
var spa = angular.module('spa', ['ngRoute']);
$scope.message = "";
spa.config(function($routeProvider) {
$scope.addAlert = function(){
$routeProvider.
$scope.alerts.push({msg: $scope.message});
when('/', {
$scope.message = "";
controller: 'WelcomeController',
}
templateUrl: 'spa/welcome.html'}).
$scope.closeAlert = function(index){
when('/hello/:id', {
$scope.alerts.splice(index, 1);
controller: 'HelloController',
}
templateUrl: 'spa/hello.html'}).
otherwise({redirecTo: '/'});
type => [success | info | warning | danger]
});
Carousel
... controllers ...
Use a <carousel> element with <slide> element inside it. It
</script>
will automatically cycle through the slides.
Navigation Template
Change hash fragment to navigate. <carousel interval="myInterval">
<slide ng-repeat="slide in slides"
<!-- welcome.html -->
active="slide.active">
<a ng-href='#/hello/{{person.id}}'>
<img ng-src="{{slide.image}}"
{{person.name}}
style="margin:auto;">
</a>
<div class="carousel-caption">
<h4>Slide {{$index}}</h4>
<!-- hello.html -->
<p>{{slide.text}}</p>
<a ng-href="#/">Back</a>
</div>
</slide>
</carousel>

PUPA & CNR, COE/PSU - V1.08 3


Script Modal
$scope.myInterval = 5000; Create a partial view, its controller and reference them.
$scope.slides = [ Template
{image: 'cat1.jpg', text: 'Cat1'},
<script type="text/ng-template" id="content.html">
{image: 'cat2.jpg', text: 'Cat2'},
<div class="modal-header">
{image: 'cat3.jpg', text: 'Cat3'},
<h3>A modal!</h3>
];
</div>
<div class="modal-body">
Date Picker
<ul>
Everything is formatted using the date filter and thus is also <li ng-repeat="item in items">
localized. <a ng-click="selected.item = item">{{ item }}
Note: include angular-locale-th.js for Thai date format. </a>
Template </li>
</ul>
<h4>Popup</h4>
Selected: <b>{{ selected.item }}</b>
<pre>Selected date is:
</div>
<em>{{dt | date:'fullDate' }}</em>
<div class="modal-footer">
</pre>
<button class="btn btn-primary"
<input type="text"
ng-click="ok()">OK</button>
class="form-control" ng-model="dt"
<button class="btn btn-warning"
datepicker-popup="{{format}}" />
ng-click="cancel()">Cancel
</button>
Script </div>
$scope.today = function() { </script>
$scope.dt = new Date(); <button class="btn btn-default" ng-click="open()">
}; Open me!
$scope.today(); </button>
$scope.format = 'dd-MMMM-yyyy'; <div ng-show="selected">
Selection from a modal: {{ selected }}
ng-model represents selected date. </div>
datepicker-popup the format for display dates
Script
Time Picker
myApp.controller('ModalDemoCtrl', function ($scope,
Settings can be provided as attributes in the <timepicker> $modal, $log) {
or globally configured through the timepickerConfig
Template $scope.items = ['item1', 'item2', 'item3'];
<pre>Time is: {{mytime | date:'shortTime'}}</pre>
<div ng-model="mytime" style="display: inline-block"> $scope.open = function () {
<timepicker hour-step="hstep" var modalInstance = $modal.open({
minute-step="mstep" templateUrl: 'content.html',
show-meridian="ismeridian"> controller: 'ModalInstanceCtrl',
</timepicker> resolve: {
</div> items: function () {
</div> return $scope.items;
}
}
Script
});
$scope.mytime = new Date();
$scope.hstep = 1; modalInstance.result.then(function(selectedItem){
$scope.mstep = 15; $scope.selected = selectedItem;
$scope.ismeridian = true; }, function () {
$log.info('Modal dismissed at: ' + new Date());
Tab });
Use <tab> directive in <tabset> directive. };
});
Template
<tabset> myApp.controller('ModalInstanceCtrl', function
<tab ng-repeat="tab in tabs" ($scope, $modalInstance, items) {
heading="{{tab.title}}" $scope.items = items;
active="tab.active"> $scope.selected = {
{{tab.content}} item: $scope.items[0]
</tab> };
</tabset>
$scope.ok = function () {
Script $modalInstance.close($scope.selected.item);
$scope.tabs = [ };
{ title:"Title 1", content:"Content 1" },
{ title:"Title 2", content:"Content 2", $scope.cancel = function () {
disabled: true } $modalInstance.dismiss('cancel');
]; };
});

PUPA & CNR, COE/PSU - V1.08 4

You might also like