Directives are snippets of HTML with their own custom JavaScript logic. Angular's concept of directives helps separate concerns and duties of code while making your views DRY and logic-less. Angular directives are very modular and can be added, shared, and swapped between projects.
After this workshop, developers will be able to:
- Understand the purpose and function of Angular directives
- Find the correct directive for a web app's needs
- Create a simple custom directive
Before this workshop, developers should already be able to:
- Implement an Angular app with a single page and single controller
Check out the AngularJS API Docs to implement a simple app.
- Begin with your intro project or create a new one
- Work in pairs to implement as many of the following directives as possible: ngClick, ngIf, ngHide, ngShow, ngModel
Sometimes when you're looking to solve a problem, you find that another developer has already made a solution in the form of a directive. Now the challenge is how to include that directive in your project.
- Add the directive's file(s) to your project.
- Include the file(s) in
index.html
. - Inject the directive into your app:
// app.js
angular.module('yourApp', ['ngResource', 'ngMap', 'pickadate', 'ui.bootstrap']);
Check out ng-modules to find popular Angular Directives to add to your project. Choose two to add with your partner.
Imagine you wanted to make a box that displayed a city's current weather that was re-useable across pages for various cities. A directive would be a great solution! Let's look at how you'd build this directive that fetches a city's weather data and displays it on the page.
Place this HTML anywhere inside your Angular controller:
<!-- index.html -->
<current-weather city="Denver"></current-weather>
Add this directive to your app (NOTE: We will cover a lot of this, such as $scope and $http, in a later lesson):
// app.js
var app = angular.module('ngCustomDirectives', []);
app.directive('currentWeather', function() {
return {
restrict: 'E',
scope: {
city: '@'
},
template: '<div class="current-weather"><h4>Weather for {{city}}</h4>{{weather.main.temp}}</div>',
// templateUrl: 'templates/currentWeatherTemplate.html',
// transclude: true,
controller: ['$scope', '$http', function($scope, $http){
var url="http://api.openweathermap.org/data/2.5/weather?mode=json&cnt=7&units=imperial&callback=JSON_CALLBACK&q=";
var apikey = "&appid="; // go generate an API key and plug it in here.
$scope.getWeather = function(city){
$http({method: 'JSONP', url: url + city + apikey})
.success(function(data){
$scope.weather = data;
});
};
}],
link: function (scope, element, attrs) {
scope.weather = scope.getWeather(attrs.city);
}
};
});
The first option in an Angular directive is the restrict
option. This option lets you specify how exactly you'd like to call the directive in HTML. See the options below; A and E are the most popular.
- A : Attribute
- E : Element
- C : Class
- M : Comment
'A' - <span current-weather></span>
'E' - <current-weather></current-weather>
'C' - <span class="current-weather"></span>
'M' - <!-- directive: current-weather -->
Using the template
and templateUrl
options you can define an HTML template inside the directive's JS or in a separate HTML file in the templates folder.
But wait a sec, how do directives interact with the $scope
set by the local controller? Can I get data from the local controller into my directive?
By default, scopes do inherit the scope of their local controller just like they were HTML in the template. However, you can use the scope
option to change this default behavior to isolate your directive's scope.
-
scope: true
- If scope is set totrue
, then the directive will have its own child scope that inherits from the parent scope of the local controller, meaning it can still access and change the parent scope. -
scope: {}
- By passing an object to thescope
option, you can define an isolated scope. Inside this object you can pass in three aliases indicating the expected datatype:
scope: {
ngModel: '=', // provides two-way binding
onSend: '&', // works with function calls
fromName: '@' // reads attribute value
}
<input type="text" ng-model="recipient.email">
<!-- invoke the directive -->
<div scope-example ng-model="recipient.email" on-send="sendMail()" from-name="[email protected]">
The controller option allows you to define a controller specific and isolated to the directive.
The link()
option is the meat and potatoes of the directive. Inside this function, you specify what you'd like the directive to do, and you can update scope.
Add this new custom directive to your app. Make sure you get an API key for the weather API. Once everything works, make it beautiful and see what other information you could include on your dynamic app.
- What are the main Angular directive options we discussed today? What do they define?
- How would you show the weather for multiple cities?
All content is licensed under a CCBYNCSA 4.0 license. All software code is licensed under GNU GPLv3. For commercial use or alternative licensing, please contact [email protected].