Tag Archives: directives

How to customize your own directive in AngularJs

AngularJS directives are what controls the rendering of the HTML inside an AngularJS application.Example of directives are the interpolation directives({{}}),the ng-repeat directive and ng-if directive.
And you also could write your own directive.

Here is a simple examle, you html code:

<greet from=”Sandy” to=”audience”></greet>

here is your directive code:

MyApp.directive(‘greet’, function () {
return {
scope: true,
restrict : ‘E’, /* restrict this directive to elements */
template: ‘<h2>Greeting from {{from}} to my dear {{to}}</h2>’,
controller: function ($scope, $element, $attrs) {
$scope.from = $attrs.from;
$scope.to = $attrs.to;
}
};
});

You output is:

2014-11-17_110348

Another example I’ve used in my TodoApp example, for the source code could go to here find it.

https://github.com/sandywebdesigner/AngularJsApp

TodoApp.directive(‘sorted’, [function () {
return {
scope: true,
restrict: ‘A’,  /* using ‘A’, when you have <div my-directive></div> in the html. */
transclude: true,
template: ‘<a class=”btn btn-link” ng-click=”do_sort()” ng-transclude></a>’ +
‘<span ng-show=”do_show(true)”>’ +
‘<i class=”glyphicon glyphicon-arrow-down”></i>’ +
‘</span>’ +
‘<span ng-show=”do_show(false)”>’ +
‘<i class=”glyphicon glyphicon-arrow-up”></i>’ +
‘</span> ‘,
controller: function ($scope, $element, $attrs) {
$scope.sort_by = $attrs.sorted;
$scope.do_sort = function() {
$scope.sort($scope.sort_by);
};
$scope.do_show = function(is_desc) {
return (is_desc != $scope.is_desc && $scope.sort_order == $scope.sort_by)
}
}
};
}]);