AngularJS调用指令功能有或没有控制器参数
我在互联网上搜索了很多,但我没有找到任何我正在寻找的好例子。这可能是由于我是angularjs中的新人。AngularJS调用指令功能有或没有控制器参数
我在看什么,我有一些常见的功能,我需要从控制器的不同情况下触发,或者可能来自不同的指令,在指令或任何事情内。
权可不是我现在有两个情况,1)上的focusIn和事件的内容我想给边境其父包装此我将这些功能:
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])(?=.*[[email protected]#\$%\^&\*])(?=.{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)你可以使用jQuery的元素element
在link
功能捕获指令的元素上的事件:
element.focus(function(event, args) {
element.parent().addClass('focus');
});
element.blur(function(event, args) {
element.parent().removeClass('focus');
});
广告2)我建议你将你的passwordStrength
功能的代码放到一个service和在您的输入元素上使用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
OP已经有这个 – Grundy
说你能提供样品plunkr? – Grundy
我的plunkr没有保存... – Mandy
你的意思是_not saving_?所以保存它:-) – Grundy