AngularJS Custom Directives
Recall: Angular Directives • Original Definition: a marker on an html tag that tells our HTML when to trigger or run our JavaScript • HTML attributes with an ng- prefix used by AngularJS to extend HTML • E.g., ng-app, ng-model, ng-bind, ng-repeat, ng-init • Better Definition: HTML annotations that trigger JavaScript behaviors
ng-include Directive • The main HTML file can become cluttered and would need to be de-cluttered. • Can have multiple pages that need to reuse some HTML snippet, e.g., product title and price. • Pull HTML snippet in separate html template file • Use ng-include to load template code where needed <h3 ng-include=”’product-title.html’” novalidate> </h3>
Cross Origin Request (CORS) problem • CORS error may surface because of protocol scheme -- file:/// • Create small express server • Will use http:// protocol scheme and resolve CORS error
Detour: Dependency manager • It is helpful to use a package manager that also manages your dependencies • Bower and npm are usable options Bower --. package manager for front-end packages o npm -- package manager for node packages o • We will use npm in this course access to more packages o > npm init o Accept as many or as few of the defaults as you want. I changed the o name, description, and entry point (server.js).
Using npm to manage dependencies • Use npm to install angular, bootstrap, express, and other packages locally • Always use the --save flag to add dependencies to package.json manifest > npm install angular@1.4.8 --save o > npm install bootstrap --save o > npm install express –save o Update the paths of the installed modules in main html file o • install nodemon globally like this: > npm install nodemon –g o nodemon is a utility module that watches your server code and restart it o as the code changes
express server 1 // We need an express application to run a webserver 2 var express = require('express'); 3 var path = require('path'); 4 var expressApp = express(); 5 6 expressApp.set("port", process.env.PORT || 3000); 7 8 // Express middleware 9 expressApp 10 .use(express.static('./')) 11 .get('*', function (req, res){ 12 res.sendFile('index.html', {root: path.join(__dirname, './')}); 13 }) 14 .listen(expressApp.get('port'), function (){ 15 console.log('Server is listening on port ' + expressApp.get('port')); 16 }); > nodemon server.js
Back to ng-include • CORS error should go away • No change in display, but the way the page is loaded changes • When URL for page request is made by the client, the server sends back the index.html file and the assets for that page • When that page loads and the ng-include directive is encountered, another request is issued to the server for that file and the HTML is returned
ng-include
Why write a directive? • Directives are the secret sauce of AngularJS • Directives allow you to write HTML that expresses the behavior of your application • By looking at the code in your main html file, you can tell what it does • Expressiveness is the real power of custom directives!!
Writing custom directives • Template-expanding Directives are the simplest: define a custom tag or attribute that is expanded or replaced o can include controller logic, if needed. o • Directives can also be used for: Expressing complex UI o Calling events and registering event handlers o Reusing common components o
How do we build custom directives 1 var app = angular.module('store', []); ... 27 app.directive('productTitle', function (){ 28 // return a configuratin object that defines 29 // how the directive will work. 30 return { 31 restrict: 'E', // Type of directive (E for HTML Element) 32 templateUrl: 'views/product-title.html’ 33 // URL to template to load into the page 34 }; 35 });
Custom Directive usage <product-title></product-title> • Note that the dash the name of a directive in your HTML will translate to camelCase in your JavaScript • Since a directive function returns a configuration object, you can add the configuration that you need • Here, we are only defining a template-expanding directive. When we use this directive, it will render the HTML into the page
Attribute vs Element Directives • Element Directive: Notice that we are not using self- closing tags. Some browsers do not like self-closing tags for custom elements. • Attribute Directive: <h3 product-title></h3> Used as an attribute of an HTML element. Change the restrict property value from ‘ E ’ to ‘ A ’ o • Best practice : Use Element Directives for UI widgets and Attribute Directives for mixin behaviors like tooltip.
Custom directives -- way to go • Custom directives allow you to write better html • When you think of a dynamic web application, do you think you'll be able to understand the functionality just by looking at the HTML? • When you're writing an AngularJS application, you should be able to understand the behavior and intent from just the HTML • Using custom directive makes our HTML more expressive
Exercise • Move the product specifications content to a product-specs.html template • Define a custom attribute directive called productSpecs to load it
What if our Directive needs a controller? • First, extract template code from main html file into a separate template file, e.g., product-panels.html • create an element directive and move controller functionality into that directive using the controller attribute • Use the controllerAs attribute to create an alias for the controller • Use the directive in the main html file where the template code was extracted
Exercise • Refactor productGallery code using an element directive with a controller • Refactor productReviews using an element directive (no controller)
Resources http://www.w3schools.com/angular/angular_directives.asp • http://www.html5rocks.com/en/tutorials/cors/ • http://www.ng-newsletter.com/posts/directives.html •
Recommend
More recommend