Sei sulla pagina 1di 4

AngularJS

HTML enhanced for web apps!

ng-show shows or hides the given HTML element based


on the expression provided. In example, isShown is a
model in bound controller.

<p ng-show="isShown">Yes!</p>

MVC

ng-click allows you to specify custom behavior when


an element is clicked. In example, recompute() is a
method in bound controller.

Model View Controller

<button ng-click='recompute()'>=</button>

Controller
Controller is defined at root scope.

<!-- Concepts of MVC -->


<html ng-app>
<head>
<script src="angular.js"></script>
</head>
<body>
<div ng-controller='HelloController'>
<p>Hello {{target}}</p>
</div>
</body>
<script type="text/javascript">
function HelloController($scope){
$scope.target = 'world'
}
</script>
</html>

<input ng-model='a' ng-change='recompute()'/>


$watch
Call $watch() with an expression to observe and a callback
that gets invoked whenever that expression changes. The
last parameter true tells deep inspection.
$scope.data = {a: 0, b:0};
...
$scope.$watch('data', $scope.recompute, true);
Form Validation

ng-controller => Bind angular controller to given


template
Angular expressions enclosed in curly braces {{ }}

Two-way Data Binding


Use ng-model directive to create a two way data-binding
between the input element and the target model.
Template
<div ng-controller='HelloController'>
<input ng-model='target'>
<p>Hello {{target}}</p>
</div>

function HelloController($scope){
$scope.target = 'world'
}

Directives

ng-repeat instantiates a template once per item from a


collection. It provides $index for index of the collection
and $first, $middle, $last as Boolean.
Template

<ul ng-controller='ListController'>
<li ng-repeat='fruit in fruits'>
{{fruit.name}} = {{fruit.amount}}
</li>
</ul>

Script

ng-class dynamically set CSS classes on an HTML


element

{{7/3 | number}}
{{7/3 | number:1}}
{{12000 | currency:'THB'}}
... ng-repeat="f in fruits | orderBy:'amount'" ...

Modules

Useful Features

function ListController($scope){
$scope.fruits = [{name: 'mango', amount: 2},
{name: 'banana', amount: 5},
{name: 'orange', amount: 4}];
}

<form name="addFruitForm">
<div>Name: <input ng-model='fruit.name' required
ng-minlength='3'></div>
<div>
Amount: <input type='number' min='1' max='10'
ng-model='fruit.amount' name='amount' required>
<span class="label label-warning"
ng-show='!addFruitForm.amount.$valid'>
1-10
</span>
</div>
<div><button ng-disabled='!addFruitForm.$valid'
ng-click='addFruit()'>Add</button></div>
</form>
Filters

Script

ng-change evaluates the given expression when the


user changes the input (evaluated immediately, not at
the end of a change)

The process is more declarative which is easier to


understand
In unit-testing there is no need to load all modules,
which may aid in writing unit-tests.
Additional modules can be loaded in scenario tests,
which can override some of the configuration and help
end-to-end test the application
Third party code can be packaged as reusable
modules.
The modules can be loaded in any/parallel order (due
to delayed nature of module execution).

var myApp = angular.module('myApp', [])


myApp.controller('Ctrl', function ($scope){
$scope.target = 'world'
});
Template must specify name of target module.
<html ng-app="myApp">
...
</html>

<tr ng-repeat='fruit in fruits'


ng-class='{highlight: $first}'>

PUPA & CNR, COE/PSU - V1.08

Module Loading
Modules can list other modules as their dependencies.
Note: include ui-bootstrap.js and bootstrap.css
Template
<div>
Focus me: <input tooltip-trigger="focus"
tooltip-placement="right" tooltip="See?"/>
</div>

Install node modules by running following


commands at project directory

>> npm install

Install MongoDB driver


Note: you might need --msvs_version option in
Windows 8

>> npm install mongodb --msvs_version=2013


Script

var myApp = angular.module('myApp',


['ui.bootstrap']);
Dependencies Injection
The simplest way to get hold of the dependencies, is to
assume that the function parameter names are the names
of the dependencies.
myApp.controller('Ctrl', function($scope, $http){
$http.get('/books').success(function(data) {
$scope.books = data;
});
});
Custom Filters
Just register a new filter factory function with your module.
myApp.filter('withSign', function(){
var filter = function(input){
if(input > 0)
return "+" + input;
else
return "" + input;
};
return filter;
});

Services
There are three functions for creating generic services, with
different levels of complexity and ability.
[provider | factory | service]
myApp.factory('Book', function(){
var book = {};
book.query = function(){
return [
{title: 'AngularJS', price: 500},
{title: 'CSS', price: 300},
{title: 'Bootstrap', price: 320}
];
};
return book;
});
myApp.controller('BookCtrl', function($scope, Book){
$scope.books = Book.query();
});

MEAN Stacks
MongoDB, Express, Angular, Node

Install & Run MongoDB


>> mongod --dbpath=data/

Install Node (npm is also installed)


Create project directory with package.json in it

{
"name": "angularjs-seed",
"description": "A starter project for AngularJS",
"dependencies": {
"express": "3.x"
},
"devDependencies": { ... }

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

>> node server.js

Communicate with Server


$http
A core Angular service that facilitates communication with
the remote HTTP servers
$http.get('/books').
success(function(data) {
$scope.books = data;
});
});
ngResource
Provide interaction support with RESTful services via the
$resource service.
Note: include angular-resource.js in your code.
var myApp = angular.module('myApp', ['ngResource']);
myApp.factory('Book', function($resource){
return $resource('books/:_id', {_id: '@_id'});
});
myApp.controller('Ctrl', function($scope, Book){
$scope.books = Book.query();
});
Default Actions
{ 'get':
'save':
'query':
'remove':
'delete':

{method:'GET'},
{method:'POST'},
{method:'GET', isArray:true},
{method:'DELETE'},
{method:'DELETE'} };

Promise
An interface for interacting with an object that represents
the result of an action that is performed asynchronously,
and may or may not be finished at any given point in time.
Note: you can chain then.
promise.then(function(greeting) {
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
}, function(update) {
alert('Got notification: ' + update);
});

Unit Testing
With great power comes great responsibility.
Karma
Install karma globally so we can run unit-testing from
command line.
>> npm install g karma
Create karma configuration files by running this command
at project directories.
>> karma init

PUPA & CNR, COE/PSU - V1.08

Answer the questions accordingly. Then create test


specifications in Jasmine syntax.

Bootstrap

describe('unit-test', function() {
it('should work', function(){
expect(true).toBe(true);
});
});

Accordion

Run the test.


>> karma start karma.conf.js
Test services and controllers
describe("myModule", function() {
var service;
var scope;
beforeEach(function(){
module('myModule');
inject(function($controller, myService){
scope = {};
$controller('myController', {$scope: scope})
service = myService;
});
});

The accordion directive builds on top of the collapse


directive to provide a list of items
Template
<label class="checkbox">
<input type="checkbox" ng-model="oneAtATime">
Open only one at a time
</label>
<accordion close-others="oneAtATime">
<accordion-group heading="{{group.title}}"
ng-repeat="group in groups" is-open="true">
{{group.content}}
</accordion-group>
</accordion>
Script
myApp.controller('Ctrl', function($scope){
$scope.groups = [
{title: "Nexus S", content: "Fast."},
{title: "MOTOROLA", content: "The Next."}
];
});

it("should know how to calculate", function() {


expect(service.plus(2, 3)).toBe(5);
});
it("should initialize lastResult", function() {
expect(scope.lastResult).toBe(0);
});
});

Routes
Though AJAX apps are technically single-page apps (in the
sense that they only load an HTML page on the first request,
and then just update areas within the DOM thereafter), we
usually have multiple sub-page views.
Note: include angular-route.js in your code.
Template
<body>
<div ng-view>
</div>
</body>
<script type="text/javascript">
var spa = angular.module('spa', ['ngRoute']);
spa.config(function($routeProvider) {
$routeProvider.
when('/', {
controller: 'WelcomeController',
templateUrl: 'spa/welcome.html'}).
when('/hello/:id', {
controller: 'HelloController',
templateUrl: 'spa/hello.html'}).
otherwise({redirecTo: '/'});
});
... controllers ...
</script>
Navigation
Change hash fragment to navigate.
<!-- welcome.html -->
<a ng-href='#/hello/{{person.id}}'>
{{person.name}}
</a>
<!-- hello.html -->
<a ng-href="#/">Back</a>

close-others to control whether expending an


item will cause the other items to close.
heading title of heading.

Alert
Directive to generate alerts from the dynamic model data.
Template
<alert ng-repeat="alert in alerts" type="alert.type"
close="closeAlert($index)">
{{alert.msg}}
</alert>
<form class="form-inline">
<div class="form-group">
<input class="form-control" type="text"
ng-model="message">
</div>
<button class="btn" ng-click="addAlert()">
Click
</button>
</form>
Script
$scope.message = "";
$scope.addAlert = function(){
$scope.alerts.push({msg: $scope.message});
$scope.message = "";
}
$scope.closeAlert = function(index){
$scope.alerts.splice(index, 1);
}

type => [success | info | warning | danger]

Carousel
Use a <carousel> element with <slide> element inside it. It
will automatically cycle through the slides.
Template
<carousel interval="myInterval">
<slide ng-repeat="slide in slides"
active="slide.active">
<img ng-src="{{slide.image}}"
style="margin:auto;">
<div class="carousel-caption">
<h4>Slide {{$index}}</h4>
<p>{{slide.text}}</p>
</div>
</slide>
</carousel>
PUPA & CNR, COE/PSU - V1.08

Script
$scope.myInterval = 5000;
$scope.slides = [
{image: 'cat1.jpg', text: 'Cat1'},
{image: 'cat2.jpg', text: 'Cat2'},
{image: 'cat3.jpg', text: 'Cat3'},
];
Date Picker
Everything is formatted using the date filter and thus is also
localized.
Note: include angular-locale-th.js for Thai date format.
Template
<h4>Popup</h4>
<pre>Selected date is:
<em>{{dt | date:'fullDate' }}</em>
</pre>
<input type="text"
class="form-control" ng-model="dt"
datepicker-popup="{{format}}" />
Script
$scope.today = function() {
$scope.dt = new Date();
};
$scope.today();
$scope.format = 'dd-MMMM-yyyy';

ng-model represents selected date.


datepicker-popup the format for display dates

Time Picker
Settings can be provided as attributes in the <timepicker>
or globally configured through the timepickerConfig
Template
<pre>Time is: {{mytime | date:'shortTime'}}</pre>
<div ng-model="mytime" style="display: inline-block">
<timepicker hour-step="hstep"
minute-step="mstep"
show-meridian="ismeridian">
</timepicker>
</div>
</div>
Script
$scope.mytime = new Date();
$scope.hstep = 1;
$scope.mstep = 15;
$scope.ismeridian = true;
Tab
Use <tab> directive in <tabset> directive.
Template
<tabset>
<tab ng-repeat="tab in tabs"
heading="{{tab.title}}"
active="tab.active">
{{tab.content}}
</tab>
</tabset>

<script type="text/ng-template" id="content.html">


<div class="modal-header">
<h3>A modal!</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items">
<a ng-click="selected.item = item">{{ item }}
</a>
</li>
</ul>
Selected: <b>{{ selected.item }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary"
ng-click="ok()">OK</button>
<button class="btn btn-warning"
ng-click="cancel()">Cancel
</button>
</div>
</script>
<button class="btn btn-default" ng-click="open()">
Open me!
</button>
<div ng-show="selected">
Selection from a modal: {{ selected }}
</div>
Script
myApp.controller('ModalDemoCtrl', function ($scope,
$modal, $log) {
$scope.items = ['item1', 'item2', 'item3'];
$scope.open = function () {
var modalInstance = $modal.open({
templateUrl: 'content.html',
controller: 'ModalInstanceCtrl',
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function(selectedItem){
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
myApp.controller('ModalInstanceCtrl', function
($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};

Script
$scope.tabs = [
{ title:"Title 1", content:"Content 1" },
{ title:"Title 2", content:"Content 2",
disabled: true }
];

Modal
Create a partial view, its controller and reference them.
Template

$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});

PUPA & CNR, COE/PSU - V1.08

Potrebbero piacerti anche