by David Loo | Apr 5, 2015 | AngularJS
What is a custom directive?
In my last post I’ve described what’s a directive and the types of directives available in AngularJS. But in AngularJS you’re not restricted to what is available, you have the ability to create you own directive too.
What are the ingredients that makes up a custom directive?
A very basic custom directive will contains the module.directive API to register it. The first parameter is the name and the second parameter is the function that returns configuration object.
Below is I have created an directive that is an element with a template that display a simple Hello, World! message in html.
angular.module('app', [])
.directive('helloWorld', function () {
return {
restrict: 'E',
template: '<b>Hello, World!</b>'
};
});
<hello-world></hello-world>
Let’s break it down. (more…)
by David Loo | Nov 22, 2014 | AngularJS
Here are some basics on how to create your own Angular custom filters. Below I have created a controller with an array of numbers starting from 1 to 10 and I am going to write a custom filter for filtering even numbers and one for odd numbers.
app.controller('AppController', ['$scope', function($scope) {
$scope.numbers = [1,2,3,4,5,6,7,8,9,10];
}
]);
To filter even numbers only I created a filter called EvenNumbersOnly which is a function that takes an array of numbers and check each value to see they are even numbers:
app.filter('EvenNumbersOnly', [function() {
return function(numbers) {
var evenNumbers = [];
for (idx in numbers)
{
if ((numbers[idx] % 2) == 0)
{
evenNumbers.push(numbers[idx]);
}
}
return evenNumbers;
}
}
]);
For filtering odd numbers I have done the same thing except it only check for odd numbers 🙂
app.filter('OddNumbersOnly', [function(){
return function(numbers) {
var oddNumbers = [];
for (idx in numbers)
{
if ((numbers[idx] % 2) == 1)
{
oddNumbers.push(numbers[idx]);
}
}
return oddNumbers;
}
}
]);
So now we have our filters ready to be used I will create a html page that will display the original complete set of numbers in the first div element, then I display a set of even numbers using the EvenNumbersOnly filter in the second div element, and then I display a set of odd numbers using the OddNumbersOnly filter in the third div element. Please note that the filter must be used with a pipe after the value you want to filter with:
<html ng-app="app.demo">
<head>
<title>Learn AngularJS - Filters</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="AppController">
<div>
Numbers: {{ numbers }}
</div>
<div>
Even Numbers: {{ numbers | EvenNumbersOnly }}
</div>
<div>
Odd Nimbers: {{ numbers | OddNumbersOnly }}
</div>
</body>
</html>
Download Source Code