javascript - How should I package plugin functions for use in a validation directive? -


i working on below validation directive, suggested me in this answer:

mybigangularapp.directive("bkngvalidation", function ($compile) {     return {         priority: 10000,         terminal: true,         link: function (scope, element, attrs) {              var validationtype = attrs.bkngvalidation;             window["addvalidationfor_" + validationtype](element);              // prevent infinite loop             element.removeattr("bk-ng-validation");             $compile(element)(scope);         }     }; }); 

then, when apply directive html element, in form, bk-ng-validation="phonenumber", directive invokes function:

function addvalidationfor_phonenumber(element) {     element.attr("ng-pattern", "/^[0-9]+$/");     element.attr("ng-minlength", 5);     element.attr("ng-maxlength", 8);     alert("yeah baby"); } 

this addvalidationfor_phonenumber in global namespace, proof of concept, looking maybe use revealing module organize become quite number of validation functions. or there other pattern should follow because working inside angular? suspect declare constant revealing module , inject directive, thought i'd ask question before going far down wrong road.

indeed not recommended use variables global scope in javascript, , absolute anti-pattern when working angularjs.

what looking service (or factory, same job in different syntax), injected directive.

mybigangularapp.service('bkservice', function() {   this.phonenumber   = function(element) { ... }   this.somethingelse = function(element) { ... } }); 

and directive becomes:

// note how bkservice injected directive in first line mybigangularapp.directive("bkngvalidation", function ($compile, bkservice) {   return {     priority: 10000,     terminal: true,     link: function (scope, element, attrs) {          var validationtype = attrs.bkngvalidation;         bkservice[validationtype](element);          // prevent infinite loop         element.removeattr("bk-ng-validation");         $compile(element)(scope);     }   }; }); 

now if directive use service one, don't need create service can wrap these functions private methods bkngvalidation:

mybigangularapp.directive("bkngvalidation", function ($compile) {    var validations = {     phonenumber:   function(element) { ... }     somethingelse: function(element) { ... }   };    return {     priority: 10000,     terminal: true,     link: function (scope, element, attrs) {          var validationtype = attrs.bkngvalidation;         validations[validationtype](element);          // prevent infinite loop         element.removeattr("bk-ng-validation");         $compile(element)(scope);     }   }; }); 

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -