I have been searching extensively on the Internet, but I have not come across any good examples that fit what I'm looking for. This could be because I am new to AngularJS.
What I need is a way to execute some common functions in different situations from either the controller or possibly from various directives, within the directive itself or any other scenario.
Currently, I have two specific situations: 1) I want to add a border to the parent wrapper when an input is focused and remove it when it's blurred. For this, I have written the following functions:
module.directive("myDirective", function(){
return {
restrict: 'A',
link: function(scope, element, attrs){
scope.focusIn = function($event){
angular.element($event.target).parent().addClass('focus');
}
scope.focusOut = function($event){
angular.element($event.target).parent().removeClass('focus');
}
});
Now, my question is how can I call these functions from HTML code. For example, if I have the following HTML snippet:
<div class="wrapper">
<input type="text" my-directive="focusin($event)">
</div>
The above code does not seem to work as expected.
My second question is similar to the first one. I have created a module for password strength where I check the strength of a password. The directive works fine, but I'm struggling with calling this directive's function from one of my controllers.
module.directive("passwordStrength", function(){
var strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");
var mediumRegex = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})");
return {
restrict: 'A',
link: function(scope, element, attrs){
scope.$watch(attrs.passwordStrength, function(value) {
if(angular.isDefined(value)){
if(strongRegex.test(value)) {
scope.strength = 'strong';
} else if(mediumRegex.test(value)) {
scope.strength = 'medium';
} else {
scope.strength = 'weak';
scope.loginForm.$invalid = true;
}
}
});
}
};
});
<input type="password" placeholder="••••••" class="input-field clearfix password" ng-focus="focusIn($event)" password-strength="focusOut($event)" ng-minlength="8" ng-maxlength="20" name="password" ng-model="loginData.password" required password-strength="loginData.password">
The code above works well for checking password strength, but I would like to trigger this code when the user submits the form using the ng-submit
function. Can you please assist me with this?