M B M B - 5 months ago 8
AngularJS Question

Javascript file in Angular App

I have a custom validation file using jQuery that I wrote myself. It is being used in a few pages on my site.
Now I need it on a part of my site that is an Angular app. I would like to include this file and it should work the same way. I cannot change the file to be a directive or other angular file because its being used on other parts of my site.

This validator works by adding classes to the inputs and the jquery watches those elements and validates after action occurs.

HTML:angularview.html

<input type="text" ng-model="vm.Email" name="email" class="required pattern" pattern_type="email" />


Javascript:
formvalidation.js

$('.required, .pattern').on('blur', function () {
if ($(this).hasClass('required') && !$(this).val()) {
addError(this, 'required');
return;
}
if ($(this).hasClass('pattern') && !isValidInput($(this).attr('pattern-type'), $(this).val())) {
addError(this, 'invalid');
return;
}
});


Question:

How can I get this javascript file to run in my angular view?

EDIT:

I will try to be clearer.

This is not a jquery plugin. This is my own javascript file and it works using jquery. I watch inputs with a specific class name and on changes, I call functions on the page to validate(see example). How would I use this in a directive or is there a way that the functions in this file can be called by adding the correct classes to my inputs?

Answer

Probably your method is not among the best practices of Angular. But I will give the answer you need.

You can very simply include your file through a script tag. Probably you should do this by the end of body to make sure the DOM is loaded when your jquery tries to bind the events.

Angular doesn't block other scripts from executing. You should only make sure that two different systems are not trying to add same event listeners to the DOM elements.

Also it would be a good idea for you to wrap your Jquery code inside a function to prevent it from littering the global space. Another advantage of such a function is that you can execute it manually when the new views are added to the DOM dynamically.

Comments