Thursday 9 July 2015

Tutorial on creating custom directive in angular js



In this tutorial, I will be explaining, how one can create custom directive in angular js. So this tutorial is for my future reference and intermediate readers out there. Other people can press ctrl + W. Thanks.


My use-case here was to add a css class if form controller is failing required validator.


<select class="reg_text2" ng-model="user.candidateeducation.education_level" required name="education_level" ng-class="{redborder: education_edit_form.education_level.$error.required}">


so every time if I want to replicate this behaviour to other input form fields. I have to copy paste with their different names. So I thought why don't use 2kg of brain ??


Just Write you custom directive!

so I create requiredclass directive which can be used as
<input type="text" ng-model="user.about_me" name = "about_me" requiredclass="redborder" /><br />

so if the field is empty it will set validators as well as add css class redborder to input element.

here I have used http://stackoverflow.com/questions/12371159/how-to-get-evaluated-attributes-inside-a-custom-directive to bind directive's value to scope . Please note the @ sign in scope which is telling to bind in one directional to parent's scope.







 .directive('requiredclass', function () {
    return {
    restrict: 'A',
    scope : {
       class_name : "@requiredclass"
    },
    require: 'ngModel',
    link: function (scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$validators.requiredclass = function(modelValue, viewValue) {
if (ngModelCtrl.$isEmpty(viewValue)) {
// consider empty models to be valid
console.log("false " +scope.class_name);
attrs.$addClass(scope.class_name);
return false;
}
else
{
attrs.$removeClass(scope.class_name);
return true;
}
};
}
};
});
Please write comments for feedback. :)

No comments:

Post a Comment