Practical AngularJS Part 2 - Sample 4
An example of a directive.
by Dave Kerr
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<div ng-app="app">
<app-status status-value="0"></app-status>
<app-status status-value="1"></app-status>
<app-status status-value="2"></app-status>
</div>
CSS
.red {
color: #CC0000;
}
.green {
color: #00CC00;
}
.orange {
color: #ffa500;
}
JavaScript
angular.module('app', [])
// Here we create a directive to show the status.
.directive('appStatus', function() {
return {
restrict: 'E',
template: '<div ng-class="statusClass">{{statusValue | status}}</div>',
scope: {
statusValue: '='
},
link: function($scope) {
switch($scope.statusValue) {
case 0: $scope.statusClass = "red"; break;
case 1: $scope.statusClass = "orange"; break;
case 2: $scope.statusClass = "green"; break;
}
}
};
})
// We're reusing the old filter from the previous example.
.filter('status', function() {
return function(input, scope) {
switch(input) {
case 0: return "Error";
case 1: return "Warning";
case 2: return "Success";
}
}
});