Directives Notes Description Value Attribute DOM manipulation

advertisement
ng-show
Directives
Value
Description
DOM manipulation directives
if this scope item contains true the element will
$scope item that contains boolean
ng-hide
$scope item that contains boolean
ng-class
$scope item that contains class name
ng-class-odd
$scope item that contains class name
ng-class-even
$scope item that contains class name
will assign the string from a scope item to every
even element in an ng-repeat.
ng-style
$scope item that contains css text.
will assign the string from a scope item that
contains css text.
ng-bind
$scope item
ng-model
$scope item
ng-bind-template
ng-bind-html
Attribute
show, false will hide.
if this scope item contains true the element will
hide, false will show.
binds a scope item containing a class name to the
class attribute.
will assign the string from a scope item to every
odd element in an ng-repeat.
Notes
to be used
within ng-repeat
iterations.
to be used
within ng-repeat
iteration.
Binding Directives
will assign the value of the $scope item into the
elements innerHTML.
changes on the item will
notify the element.
binds the element to a scope item, every change on
the element value will notify the item updating it
accordingly.
same as using
{{}} only as an
attribute.
space separated expressions containing
scope items.
allows binding several scope items to the view in a
desired order, trough an html attribute rather than
expressions.
$scope item that contains html string.
will populate the element with the html string in
the scope item, will not print that as a string but as
an html element.
value syntax:
ng-bindtemplate
="{{scopeItem1}
}
{{scopeItem2}}"
innerHTML will
be
" scopeItem1
scopeItem2"
only if you are
appending html
strings.
can only be
used with
input,select
& textarea
elements.
Mouse Events
ng-click
$scope function
gets a function activation expression that will be
called when element is click, can get as params
items on scope or on the ng-repeat sequence.
ng-mouseover
$scope function
ng-mousein
$scope function
ng-mouseout
$scope function
gets a function activation expression that will be
called when element is click, can get as params
items on scope or on the ng-repeat sequence.
gets a function activation expression that will be
called when element is click, can get as params
items on scope or on the ng-repeat sequence.
gets a function activation expression that will be
called when element is click, can get as params
items on scope or on the ng-repeat sequence.
ng-disabled
$scope item with Boolean
value syntax:
ngclick="handleEv
ent(repeatItem)
"
Input Boolean Attributes
diables input according to a Boolean value
only on input
elements
ng-selected
$scope item with Boolean
ng-checked
$scope item with Boolean
ng-readonly
$scope item with Boolean
ng-submit
$scope function
ng-form
no value needed
sets the selected property of a radio btn according
to a Boolean value
sets the checked property of a checkbox according
to a Boolean value
set the readonly attribute of an input text element
or a textarea according to a Boolean.
radio element
checkbox
element
input[text] &
texterea
elements
Form Directives
an event handler defined on the scope to handle
the submit event of a form.
enables form nesting (form within form) by
including this attribute in the nested forms wraping
element
no value needed
URL Directives
ng-src
scope item containing URL
ng-href
scope item containing URL
delays the http request of the src attribute for
when angulars has fully loaded and can parse the
expersion within the curly braces
delays the http request of the href attribute for
when angulars has fully loaded and can parse the
expersion within the curly braces
ngsrc="{{urlItem}}"
ng-href
="{{urlItem}}"
Unique Directives
ng-cloak
no value
will display none the element until angular is
loaded and parsed the
ng-non-bindable
no value
will tell angular not to parse the contents of this
tag. Will print angular syntax.
ng-app
no value Or module name
tells angular ether that this tag contains the
angular app, Or if a module name is passed that
this tag is managed by a certain angular module.
for use when
slower client
show unrender
expressions,
best to include
on body.
Create you own Directives
The javascript:
var app = angular.module('myModule');
app.directive('DirectiveName',function(){
return {
restrict:"E",
template:"<div>This my template for this directive</div>"
};
});
The HTML
<div ng-app="app">
<DirectiveName></DirectiveName>
</div>
* Restrict:"E" = Means – restrict the directive format to Element format, using ng-DirectiveName or class="ng-Directive name
wont work".
* restrict:"A" is more commonly used. It will restrict the directive format to an Attribute.
When using restrict:"A" you'll need to provide a link:function(scope,element){} property, which will contain the behavior of
the directive.
* the two parameters passed to the link: function are used as the current scope & the element which the directive is
activated upon, the scope being the first param & the element being the second param.
* and the last restrict option is "C" for class, which will restrict the directive to the HTML class attribute, this works the same
as "A" providing the object with a link property to hold the directives functionality.
* template:'<div>text</div>' = an html template that will automatically be inserted into the <DirectiveName> tag.
*Isolate scope – when you create a directive and use it several times on your page, the controllers $scope object (passed in
to the "link" function as first argument) will be shared among all the directives of the same name on the page. This situation
can lead to a problem where each directive overwrites the other directives on the page. To solve this problem we need to
pass in a literal object ({}) to the app.directive function (in the return object, where we specified restrict & link ) as a property
named "scope" etc: {restrict:"E",scope:{}}. This will use the passed in object as the unique scope for that directive instance,
and will solve the problem of shared scope between directives.
* Directive attributes – you can get the directives special attributes to the isolate scope by declaring them on the scope ocject
literal as properties: <directive mytattribute="somthing"></directive> , scope:{myattribute:"@"}. When doing so you must
specify in the declaration what syntax is the property expacting, this is done by using "@","=" or "&" ass values when
declaring the properties on isolate scope.
** "@" – the property will expect the string syntax value passed in from the property. Etc: myattribute={{property ||
'string'}}.
** "=" – will expect an identifier syntax, and will create a two way binding to that object on the parent scope. Etc :
myattribute="myproperty", myproperty is on the controller $scope and any change to it will also change the myattribute on
the isolate scope. This is a way to override the isolated scope, defining properties on it from the controllers $scope. This is an
undoing of the isolation which we want to avoid most time, to create reusable directives which can implamented multiple
times on a page, without overriding the different directive instances data.
** "&" – will expect an identifier on the parent scope. This symbol will the directive to evaluate the value passed in from the
attribute on the parent $scope object of the controller. This provides a way to communicate between the directive and the
controller. Etc: <directive dial="doSomething(msg)"></directive> , {scope:{dial:'&'},template:"<input ngbind='value'></input><button ng-click="dial({msg:value})"></button>", value:''}. In this example, we pass the doSomething()
function from the parent scope to the directive. Than in the template provided to the directive we first bind to the value
property on the isolate scope, the we add a click event to the button which will trigger the dial property on the isolate scope.
The dial property is actually the controllers doSomthing function, and it will be triggerd passing in an object, using the param
name as key and the isolate scope property as value.
* transclusion – Most of the time when writing directives the Element format will be used, and when providing a template
attribute to the directive constructor, the template will replace the directive tags content in the html page.
If you want the directives template to be added and not replace the content you need to define transclude property on the
isolate scope passing it a property of true. Etc scope:{transclude:true} .
Injection name
Description
Services
Methods
XHR services
Notes
$http
Provides an api to make XHR requests asynchly.
$http.get('URL')
$http.post('URL',{data:'someData'})
$http.get().error(function(data,status,headers,config){})
$http.get().success(function(data,status,headers,config)
{})
the error() and
success() methods
are used the same
way for post() as
for get().
$httpProvider
the $httpProvider.defaults.headers object
contains all the default headers for HTTP
requests. To change the default headers you need
to access this objects properties and change them
accordingly.
$httpProvider.defaults.headers.common.accept =
"text/plain "
$httpProvider.defaults.headers.post.contentType =
this are just some
of the options you
can set, for a full
documentation
refer to the
angular site.
the $q service provides a way creating syncronus
XHR request. This is done using a design pattern
called Promise, which returns a promise object
imidiatly as the XHR is created. That object then
behaves like a proxy, waiting for updates from the
XHR.
$q.deffer()
$q
"application/json"
$httpProvider.defaults.headers.common.put.contenttyp
e = "application/json"
$q.deffer().resolve(data)
$q.deffer().notify(data)
$q.deffer().reject(data)
$q.deffer().then(successCallback, errorCallback,
notifyCallback)
resolve,notify &
reject are
publishers of the
data sent back
from the server on
HTTP status
changes. Then() is
used to trigger
event handlers for
thos http status
changes (the
callbacks).
Routing services
$routeProvide
r
provides the methods to set up a routing system.
This module uses the location change event and
the hash param to load controllers and templates.
The module also uses a chaching mechanism to
create history management.
$routeProvider.when('hashParam/:cbParam',
{
controller:'MyController',
template:'templateURI/templateHTML.html'
});
$routeProvider.otherWise('/');
$route
$routeParams
contains the params of the current template and
location. You can change these params to make
changes to the template reflowing the controller
with updated params. Params include
current.params,current.templateUrl,current.scope.
name
provides the params passed in trough the hash
using the colons (:). It returns a value key object.
$route.current.params
$route.current.templateUrl
$current.scope.name
$routeParams == {if:'a_1',name:'some
name'}
$routeProvider.otherWise()
will redirect the user to the
defined hash.
You can pass the when()
method params using colons
(:), than in your controller
you can access thos params
using the $routeParams
service.
You can use these to change
data for the template after it
has loaded.
unlike $route.current.params
changing these values will not
cause a reflow of the
template.
Inner angular services – used by angular and provided for deverlopers
$compile
$parse
this service is used internally by angular to parse
loaded html identifying angular directives and
bindings. This service can also be used by the
developer inside custom directives or controllers
to parse angular html.
$parse is used by angular to parse expressions
provided in the html as strings. The expression is
passed to $parse() as first param and the return
value is a function containing the expression. So in
order to evaluate that expression we need to
executed the return value. You can than pass a
context object to the returned function to
evaluate the expression in a certain context.
$compile(markup)
var obj1 = {scopeModel:{item:'0+1'}};
var obj2 = {scopeModel:{item:'1+1'}};
var getter = $parse('scopeModel.item');
// (getter( obj1) === 1) === true
// (getter( obj2) === 2) === true
Localization Date & Compatibility
returns the parsed html
you can also pass in another
context as 2nd param, to be used as
a local context. This means that the
expression resultion will search
first the second param, and only it
wont find a matching value it will
search the first param.
// (getter( obj2,obj1) === 1) ===
true
$locale
contains local formats of date currency etc…
$locale.DATETIME_FORMATS.fullDate
$locale.DATETIME_FORMATS.shortDate
$timeout
similar to the windows setTimeout function in
syntax. The difference is that the windows
setTimeout function is not operating within the
angular namespace, thus making it unaware of
angular variables or changes.
exceptionHandler unlike other services is a service
ment to be overridden by a custom function.This
is made by creating a factory function that has the
same name, or by injecting the original into a
controller and redefining it within the controller.
var promise =
$timeout(function(){},3000);
var cancel = function(){
promise.cancel()}
$exceptionHa
ndler
myModule.factory('$exceptionHandler
',function(exception){
console.log( exception.messege);
});
to switch to your own locale
language settings you need to
download a locale file for your
language from:
http://code.angularjs.org/1.0.2/i19
n/
you then need to add that script to
your page. angularJs does'nt
support, as of now, a dynamic
locale service.
we need to overwrite the default
service with our own.
Important services
$apply
$watch
Writing your own service
myApp.factory('serviceName',[
'dependency1',
'dependency2',
function( dependency1, dependency2){
var privateMethod = function(string){};
var privateProperty = "string";
//return an api to use for the service
return {
parseString: function(){ privateMethod ( privateProperty)},
string: privateProperty
}
}
]);
Filters
Expression
Description
Notes
{{stringItem |
uppercase}}
{{stringItem |
lowercase}}
will format strings in uppercase
{{numItem | number:2}}
will transform any number to a decimal number with the
number of decimel places after the colon
{{timestamp |
date:"medium"}}
{{numberItem |
currency}}
will transform a javascript timestamp into a regular date
using the format name after the colon.
{{jsonObject | json}}
will format a Jason object to a json string and print it.
String Formating
will format strings in lower case
Number Formating
will attach a currency sign to the number
Object Formating
example:
{{3 | number:2}} = 3.00
{{3.143256 | number:2}} = 3.14
the are a few date format names for further info on
them check angular documentation.
for more info on how the currency symbol is set
check angular documentation.
Sorting Filters (used with ng-repeat)
will sort items in an angular repeat according to the item
property after the colon.
item in items |
orderBy:sortItem
since there is a binding between the model and the
view, sorting will take place even on changes to the
model after rendering.
Writing your own filters
moduleName.filter('filterName',
function(inputVal/*, other params after the colon*/){
//filter logic
return modifiedValue;
}
);
//to inject your filter into your controller use one of the following syntax
1)
someModule.controller('MyController', [
'$scope',
'myFILTER',
function($scope, myFILTER){}//controller
]);
2)
MyController.$inject = ['$scope', ' myFILTER '];
3)
someModule.controller('MyController', function($scope, myFILTER) {
// ...
});
Examples & Remarks
Description
Remarks
Subject
The dot operator in
bindings
You should always build your model on a designated property on the $scope object, i.e $scope.model 
$scope.model.yourData . This is because the $scope is not ment to be a model, it’s a scope object provided to your
controller, which contains the view scope you assigned the controller to. Defining model attributes directly on $scope can
lead to some unintended behavior, such as overwriting when using ng-model.
So always designate a $scope property to hold your model properties, i.e
$scope.model.modelData1,$scope.model.modelData2 .
Examples
Creating a query
filter using ng-model
& ng-repeat.
The following example creates a query filter, it will display data according to the text you input, minimizing results as you
continue writing by filtering the ng-repeat results.
The json:
$scope.model. apocalypseNow = [
{
name:'Charlie Shien',
role:'Main character'
},
{
name:'John Doe',
role:'Side Kick'
}
]
The html:
<div ng-controller="myController">
<input type="text" ng-model="model.inputName">
<ul>
<li ng-repeat="actor in model.apocalypseNow | filter : model.inputName">
{{ actor.name }}
</li>
</ul>
</div>
Modules
Description
Remarks
Subject
Simple application
module creation.
var app = angular.module('myApp',['dependencies']);
Scalable application / In bigger applications its better to devide app into multiple modules, each contained in its own name space on the main
module. The main module "app", is dependent now on the sub modules, and dependency injection is needed when
bigger applications.
registering the main "app" module:
var myDirectives = angular.module('app.myDirectives');
var myApp = angular.module('app',['app.myDirectives']);
*notice how the 'app.myDirectives' module is declared first, that is because 'app' will need it as dependency.
Examples
Download