[英]AngularJS calling Directive function with or without parameter from Controller
我在Internet上搜索了很多東西,但是我沒有找到關於我正在尋找的任何好例子。 這可能是由於我是angularjs的新手。
我在看什么,我有一些通用功能,我需要在與控制器不同的情況下觸發,或者可能來自不同的指令,指令內或任何其他情況。
對,不是,我有兩種情況,1)關於focusin和focusout,我想為此為其父包裝器賦予邊界,我正在編寫以下功能:
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');
}
});
現在,問題是如何從html代碼調用這些函數,就像我擁有html代碼一樣:
<div class="wrapper">
<input type="text" my-directive="focusin($event)">
</div>
由於,以上代碼無法正常工作。
現在第二個問題與上面類似。 我已經創建了密碼強度模塊。 我在哪里檢查密碼強度。 該指令工作正常,但是我無法從我的控制器之一調用此指令功能。
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">
上面的代碼可以很好地實現密碼強度,但是我想在用戶提交表單時調用上面的代碼,並且ng-submit
函數應該調用密碼強度函數。 請在這方面幫助我。
希望我能正確理解您的問題;
廣告1),您可以在link
函數中使用jQuery element element
來捕獲指令元素上的事件:
element.focus(function(event, args) {
element.parent().addClass('focus');
});
element.blur(function(event, args) {
element.parent().removeClass('focus');
});
廣告2)我建議您將passwordStrength
函數的代碼移到服務中,並在輸入元素上使用ng-change
調用該函數。
1)這是dom指令的基本版本,該指令將焦點設置為背景色。
.directive('domDirective', function () {
return {
restrict: 'A',
link: function ($scope, element, attrs) {
element.on('focus', function () {
element.css('background-color', 'yellow');
});
element.on('blur', function () {
element.css('background-color', 'white');
});
}
};
});
您可以按照此Plunker進行操作。
2)我的建議將如本JSFiddle中所述
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.