ANGULARJS - Microsoft

3y ago
56 Views
3 Downloads
1.37 MB
14 Pages
Last View : 1d ago
Last Download : 3m ago
Upload by : Asher Boatman
Transcription

ANGULARJSCHEAT SHEETAngularJS is an extensible and exciting new JavaScript MVC framework developed by Google forbuilding well-designed, structured and interactive single-page applications (SPA). It lays strongemphasis on Testing and Development best practices such as templating and declarative bi-directionaldata binding.This cheat sheet co-authored by Ravi Kiran and Suprotim Agarwal, aims at providing a quick reference tothe most commonly used features in AngularJS. It will also make you quickly productive with Angular.This article is from the Free DNC Magazine for .Net and JavaScript developers. Subscribe tothis magazine for free (using only your email address) and download all the editions.BEGINNER01 Important AngularJS Components and theirusage:02Bootstrapping AngularJS application:Bootstrapping in HTML: angular.module() defines a module Module.controller() defines a controller Module.directive() defines a directive Module.filter() defines a filter Module.service() or Module.factory() orModule.provider() defines a service Module.value() defines a service from an existingobject Module div ng-app ”moduleName” /div Manual eName”])03Expressions:{{ 4 5 }} - yields 9 ng-app attribute sets the scope of a module ng-controller attribute applies a controller to theview scope service passes data from controller to theview filter service uses a filter ng-app attribute sets the scope of the modulewww.dotnetcurry.com/magazine{{ name }} - Binds value of name from currentscope and watches for changes to name{{ ::name }} - Binds value of name from currentscope and doesn’t watch for change (Added inAngularJS 1.3)01

04Module:Create a module named myModule1 that depends onmyModule2 and ule2”,“myModule2”])svc.addCity function(city){cities.push(city);};svc.getCities function(){return cities;}});Get reference to the module myModule1angular.module(“myModule1”)05The members added to instance of the service are visible to theoutside world. Others are private to the service. Services areDefining a Controller and using it:singletons, i.e. only one instance of the service is created in thelifetime of an AngularJS application.i. With yModule”).function( scope,){factory(“sampleFactory”, function(){//Members to be used in view for bindingvar cities [“New Delhi”, “Mumbai”, scope.city ”Hyderabad”;“Kolkata”, “Chennai”];});function addCity(city){cities.push(city);}function getCities(){return cities;}In the view:return{getCities: getCities, div ng-controller ”SampleController” addCity:addCity !-- Template of the view with binding};expressions using members of scope -- }); div {{city}} /div /div A factory is a function that returns an object. The membersii. Controller as syntax:that are not added to the returning object, remain privateto the factory. The factory function is executed once and theresult is stored. Whenever an application asks for a factory, theangular.module(“myModule”).application returns the same object. This behavior makes thecontroller(“SampleController”, function(){factory a singleton.var controllerObj this;//Members to be used on view for bindingcontrollerObj.city ”Hyderabad”;Value:});08In the view: div ng-controller ”SampleController as ctrl” div {{ctrl.city}} /div /div 06Defining a mpleValue”, {cities : [“New Delhi”, “Mumbai”, “Kolkata”,“Chennai”],addCity: function(city){cities.push(city);},getCities: function(){return cities;}});A value is a simple JavaScript object. It is created just once, sovalue is also a singleton. Values can’t contain private members.angular.module(“myModule”).All members of a value are public.service(“sampleService”, function(){var svc this;var cities [“New Delhi”, “Mumbai”,“Kolkata”, “Chennai”];02www.dotnetcurry.com/magazine

09Constant:application. Services, Factories and values are not availablefor config block as they are not created by this time. Onlyangular.module(“myModule”). providers and constants are accessible inside the config block.constant(“sampleConstant”,{pi: Math.PI});Config block is executed only once in the lifetime of an Angularapplication.A constant is also like a value. The difference is, a constant canbe injected into config blocks, but a value cannot be injected.1012Run function( anyservices, factories plication is configured. Now inside runprovider(“samplePrd”, function(){block”);this.initCities function(){});console.log(“Initializing Cities ”);};Run block is used to initialize certain values for furtherthis. get function(){var cities [“New Delhi”, “Mumbai”,“Kolkata”, “Chennai”];function addCity(city){cities.push(city);}function getCities(){return cities;}return{ getCities: getCities,addCity:addCity};}});A provider is a low level recipe. The get() method of theprovider is registered as a factory. Providers are availableuse, register global events and anything that needs to run atthe beginning of the application. Run block is executed afterconfig block, and it gets access to services, values and factories.Run block is executed only once in the lifetime of an odule”).filter(“dollarToRupeee”, function(){return function(val){return “Rs. “ val * 60;};});to config blocks and other providers. Once applicationconfiguration phase is completed, access to providers isUsage:prevented. span {{price dollarToRupee}} /span After the configuration phase, the get() method of theFilters are used to extend the behavior of binding expressionsproviders are executed and they are available as factories.and directives. In general, they are used to format values or toServices, Factories and values are wrapped inside provider withapply certain conditions. They are executed whenever the value get() method returning the actual logic implemented insidebound in the binding expression is updated.the provider.11Config on(samplePrdProvider, og(sampleConstant.pi);});Config block runs as soon as a module is loaded. As the nameitself suggests, the config block is used to configure le.directive(“directiveName”, function(injectables) {return {restrict: “A”,template: “ div /div ”,templateUrl: “directive.html”,replace: false,transclude: false,scope: false,03

require: [“someOtherDirective”],controller: function( scope, element, attrs, transclude, otherInjectables) { . },link: function postLink(scope, iElement,iAttrs) { . },priority: 0,terminal: false,compile: function compile(tElement, tAttrs,transclude) {return {pre: function preLink(scope, iElement,iAttrs, controller) { . },post: function postLink(scope,iElement, iAttrs, controller) { . }}}};});Directives add the capability of extending HTML. They are themost complex and the most important part of AngularJS. Adirective is a function that returns a special object, generallytermed as Directive Definition Object. The Directive DefinitionObject is composed of several options as shown in the abovesnippet. Following is a brief note on them: restrict: Used to specify how a directive can be used. Possiblevalues are: E (element), A (Attribute), C (Class) and M (Comment).Default value is A template: HTML template to be rendered in the directive templateUrl: URL of the file containing HTML template of theof the current directive. controller: Controller for the directive. Can be used tomanipulate values on scope or as an API for the currentdirective or a directive requiring the current directive priority: Sets priority of a directive. Default value is 0.Directive with higher priority value is executed before adirective with lower priority terminal: Used with priority. If set to true, it stops executionof directives with lower priority. Default is false link: A function that contains core logic of the directive.It is executed after the directive is compiled. Gets accessto scope, element on which the directive is applied (jqLiteobject), attributes of the element containing the directive andcontroller object. Generally used to perform DOM manipulationand handling events compile: A function that runs before the directive is compiled.Doesn’t have access to scope as the scope is not created yet.Gets an object of the element and attributes. Used to performDOM of the directive before the templates are compiled andbefore the directive is transcluded. It returns an object with twolink functions:o pre link: Similar to the link function, but it is executedbefore the directive is compiled. By this time, transclusion isappliedelement replace: Boolean value denoting if the directive element is too post link: Same as link function mentioned above15Most used built-in directives:be replaced by the template. Default value is false. transclude: Boolean value that says if the directive should ng-app: To bootstrap the applicationpreserve the HTML specified inside directive element afterrendering. Default is false ng-controller: To set a controller on a view scope: Scope of the directive. It may be same as the scope of ng-view: Indicates the portion of the page to besurrounding element (default or when set to false), inheritedupdated when route changesfrom scope of the surrounding element (set to true) or anisolated scope (set to {}) ng-show / ng-hide: Shows/hides the content withinthe directive based on boolean equivalent of value require: A list of directive that the current directive needs.assignedCurrent directive gets access to controller of the requireddirective. An object of the controller is passed into link function04 ng-if: Places or removes the DOM elements underwww.dotnetcurry.com/magazine

this directive based on boolean equivalent of valueassigned ng-model: Enables two-way data binding on anyinput controls and sends validity of data in the inputcontrol to the enclosing form16AngularJS Naming Conventions While naming a file say an authentication controller,end it with the object suffix. For eg: an authenticationcontroller can be renamed as auth–controller.js.Similar service can be called as auth-service.js,directive as auth-directive.js and a filter as auth-filter.js ng-class: Provides an option to assign value of Create meaningful & short lower case file names that alsoa model to CSS, conditionally apply styles and usereflect the folder structure. For eg: if we have a login controllermultiple models for CSS declarativelyinside the login folder which is used for creating users, call itlogin-create-controller.js ng-repeat: Loops through a list of items and copiesthe HTML for every record in the collection Similar a testing naming convention that you could followis if the filename is named as login-directive.js, call its test file ng-options: Used with HTML select element tocounterpart as login-directive test.js. Similarly a test file forrender options based on data in a collectionlogin-service.js can be called as login-service test.jsUse a workflow management tool like Yeoman plugin for ng-href: Assigns a model as hyperlink to an anchorAngular that automates a lot of these routines and much moreelementfor you. Also look at ng-boilerplate to get an idea of the projectand directory structure. ng-src: Assigns a model to source of an imageelement17 ng-click: To handle click event on any elementAngularJS has a built-in dependency injector that keeps trackDependency Injection:of all components (services, values, etc.) and returns instances ng-change: Requires ng-model to be presentof needed components using dependency injection. Angular’salong with it. Calls the event handler or evaluates thedependency injector works based on names of the components.assigned expression when there is a change to valueof the modelA simple case of dependency injection: ng-form: Works same as HTML form and allowsmyModule.controller(“MyController”, function( scope, window, myService){});nesting of forms ng-non-bindable: Prevents AngularJS fromcompiling or binding the contents of the current DOMelement ng-repeat-start and ng-repeat-end: Repeats top-levelattributes ng-include: Loads a partial viewHere, scope, window and myService are passed into thecontroller through dependency injection. But the above codewill break when the code is minified. Following approach solvesit:myModule.controller(“MyController”, [“ scope”,“ window”, “myService”,function( scope, window, myService){}]); ng-init: Used to evaluate an expression in the current scope ng-switch conditionally displays elements ng-cloak to prevent Angular HTML to load beforebindings are applied.www.dotnetcurry.com/magazine05

1821RoutesSome useful utility functions angular.copy - Creates a deep copy of sourceRoutes in AngularJS application are defined using routeProvider. We can define a list of routes and set one ofthe routes as default using otherwise() method; this route angular.extend - Copy methods and properties from onewill respond when the URL pattern doesn’t match any of theobject to anotherconfigured patterns. angular.element - Wraps a raw DOM element or HTML stringas a jQuery element19 angular.equals - Determines if two objects or two values areRegistering routes:equivalentmyModule.config(function( routeProvider){ plates/home.html”,controller: “HomeController”}).when(“/details/:id”, ”ListController”}).otherwise({redirectTo: “/home”});}); angular.forEach - Enumerate the content of a collection angular.toJson - Serializes input into a JSON-formatted string angular.fromJson - Deserializes a JSON string angular.identity - Returns its first argument angular.isArray - Determines if a reference is an Array20 angular.isDate - Determines if a value is a dateRegistering services:Angular provides us three ways to create and register angular.isDefined - Determines if a reference is definedourown Services – using Factory, Service, and Provider. They are all angular.isElement - Determines if a reference is a DOMused for the same purpose. Here’s the syntax for all the three:elementService: module.service( ‘serviceName’, function );Factory: module.factory( ‘factoryName’, function );Provider: module.provider( ‘providerName’, function ); angular.isFunction - Determines if a reference is a FunctionThe basic difference between a service and a factory is thatservice uses the constructor function instead of returning afactory function. This is similar to using the new operator. Soyou add properties to ‘this’ and the service returns ‘this’.With Factories, you create an object, add properties to it andthen return the same object. This is the most common way ofcreating Services.If you want to create module-wide configurable serviceswhich can be configured before being injected inside other angular.isNumber - Determines if a reference is a Number angular.isObject - Determines if a reference is an Object angular.isString - Determines if a reference is a String angular.isUndefined - Determines if a reference is undefined angular.lowercase - Converts the specified string to lowercase angular.uppercase - Converts the specified string touppercasecomponents, use Provider. The provider uses the get functionto expose its behavior and is made available via dependencyinjection.06www.dotnetcurry.com/magazine

22 http: http is Angular’s wrapper around XmlHttpRequest. It providesa set of high level APIs and a low level API to talk to RESTservices. Each of the API methods return q promise object.Following are the APIs exposed by http: http. get(url): Sends an HTTP GET request to the URLspecified http.post(url, dataToBePosted): Sends an HTTP POSTrequest to the URL specified http.put(url, data): Sends an HTTP PUT request to the URLspecified http.patch(url, data): Sends an HTTP PATCH request to theURL specified http.delete(url): Sends an HTTP DELETE request to the URLspecified http(config): It is the low level API. Can be used to sendany of the above request types and we can also specify otherproperties to the request. Following are the most frequentlyused config options:o method: HTTP method as a string, e.g., ‘GET’, ‘POST’, ‘PUT’, etc.o url: Request URLo data: Data to be sent along with requesto headers: Header parameters to be sent along with therequesto cache: caches the response when set to trueFollowing is a small snippet showing usage of http: turn result.data;}, function(error){return error;});www.dotnetcurry.com/magazine07

INTERMEDIATE - ADVANCED q.reject(reason) - Creates a promise that is resolved as23that the promise continues to the next error handler instead ofManage Dependenciesrejected with the specified reason. The return value ensuresa success handler.Use a package management tool like Bower (bower.io/) to deferredObject.resolve - Resolves the derived promise withmanage and update third-party web dependencies in yourthe valueproject. It is as simple as installing bower using npm installbower; then listing all the dependent libraries and versions in a deferredObject.reject - Rejects the derived promise with theBower package definition file called bowerconfig.json and lastlyreason and triggers the failure handler in the promise.run bower install or bower update in your project to get thelatest versions of any web dependencies in your project.24Using AngularJS functionsWherever possible, use AngularJS versions of JavaScriptfunctionality. So instead of setInterval, use the intervalservice. Similarly instead of setTimeout use the timeoutservice. It becomes easier to mock them or write unit tests . Also27Manipulating scopeDo not make changes to the scope from the View. Instead do itusing a Controller. Let’s see an example. The following piece ofcode controls the state of the dialog property directly from theng-click directive. destroy event to do so: div button ng-click ”response false” Close Dialog /button /div scope. on(“ destroy”, function (event) { timeout.cancel(timerobj);});Instead we can do this in a Controller and let it control themake sure to clean it up when you have no use for it. Use the25ServicesIf you need to share state across your application, or need asolution for data storage or cache, think of Services. Servicesare singletons and can be used by other components such asdirectives, controllers, filters and even other services. Servicesdo not have a scope of their own, so it is permissible to addstate of the dialog as shown here: div button ng-click ”getResponse()” Close Dialog /button /div In dialog-controller.js file, use the following code:dialog.controller(“diagCtrl”, function ( scope) { scope.response false;eventlisteners in Services using rootScope.26 scope.getResponse function () { scope.response false;}Deferred and PromiseThe q service provides deferred objects/promises. q.all([array of promises]) - creates a Deferred object that isresolved when all of the input promises in the specified arrayare resolved in future q.defer() - creates a deferred object with a promise propertythat can be passed around applications, especially in scenarioswhere we are integrating with a 3rd-party library});This reduces the coupling between the view and controller28Prototypal InheritanceAlways have a ‘.’ in your ng-models which insuresprototypal inheritance. So instead of input type ”text” ng-model ”someprop” use input type ”text” ng-model ”someobj.someprop” 08www.dotnetcurry.com/magazine

29Event Aggregator:certain interval. If count is not passed, it defaults to 0, whichcauses the call to happen indefinitely. scope includes support for event aggregation.

AngularJS is an extensible and exciting new JavaScript MVC framework developed by Google for building well-designed, structured and interactive single-page applications (SPA). It lays strong emphasis on Testing and Development best practices such as templating and declarative bi-directional data binding. This cheat sheet co-authored by Ravi Kiran and Suprotim Agarwal, aims at providing a quick .

Related Documents:

AngularJS uses dependency injection and make use of separation of concerns. AngularJS provides reusable components. AngularJS viii With AngularJS, the developers can achieve more functionality with short code. In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing. On the top of everything, AngularJS applications can run on all major browsers .

AngularJS Tutorial W3SCHOOLS.com AngularJS extends HTML with new attributes. AngularJS is perfect for Single Page Applications (SPAs). AngularJS is easy to learn. This Tutorial This tutorial is specially designed to help you learn AngularJS as quickly and efficiently as possible. First, you will learn the basics of AngularJS: directives, expressions, filters, modules, and controllers. Then you .

Beginning AngularJS Beginning AngularJS is your step-by-step guide to learning the powerful AngularJS JavaScript framework. AngularJS is one of the most respected and innovative frameworks for building properly structured, easy-to-develop web applications. This book will teach you the absolute essentials, from downloading and installing AngularJS, to using modules, controllers, expressions .

AngularJS provides data binding capability to HTML thus giving user a rich and responsive experience AngularJS code is unit testable. AngularJS uses dependency injection and make use of separation of concerns. AngularJS provides reusable components. With AngularJS,

AngularJS Tutorial, AngularJS Example pdf, AngularJS, AngularJS Example, angular ajax example, angular filter example, angular controller Created Date 11/29/2015 3:37:05 AM

AngularJS team at Google as an external contractor and is a founder member of the AngularUI project. He has spoken about AngularJS at Devoxx UK and numerous London meetups. He also runs training courses in AngularJS. His consultancy practice is now primarily focused on helping businesses make best use of AngularJS. I would like to thank the team at Google for giving us AngularJS, in particular .

Code Explanation for ng-transclude Directive in AngularJS: 1. The ng-app specifies the root element ( myApp ) to define AngularJS . ng-transclude directive is used to include the existing content "AngularJS" . Sample Output for ng-transclude Directive in AngularJS: 1. The content welcome to wikitechy is displayed in the output using the .

AngularJS is a JavaScript framework. It is a library written in JavaScript. AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag: [3] AngularJS extends HTML with ng-directives. The ng-app directive defines that this is an AngularJS application.