我有一个全局指令,负责从 Controller 获取错误消息,编译并显示它。
如果出现服务器验证错误,例如
此电子邮件已存在
,我想关注此元素,并将其有效性设置为 false,例如$setValidity(false)
.
该指令不是表单,也不包含表单。
你有什么建议(已经尝试了注释掉的所有内容)
directive('messageCompile', function ( $compile, $window, $rootScope ) {
return {
restrict: 'A',
scope: true,
link: function ( scope, element, attrs ) {
var el;
attrs.$observe( 'template', function ( tpl ) {
if ( angular.isDefined( tpl ) ) {
// compile the provided template against the current scope
el = $compile( tpl )( scope );
// stupid way of emptying the element
element.html("");
// add the template content
element.append( el );
}
});
attrs.$observe('focus', function(val){
if ( angular.isDefined( val ) && Boolean(val)) {
var el = angular.element('[name="' + attrs.focus + '"]');
var form = el.parents().find('form');
var formName = form.attr('name');
el.focus();
// scope[formName].$setValidity(val, false);
// el.scope().$setValidity(false);
// scope[formName][val].$setValidity(false);
//$rootScope.scope[formName][val].$setValidity(false);
//$rootScope.scope[formName].$setValidity(val, false);
}
});
var windowEl = angular.element($window);
windowEl.on('scroll', function() {
if(window.scrollY > 46){
element.parent().parent().addClass('stayTop');
// alert('here');
}
else{
// alert('here2');
element.parent().parent().removeClass('stayTop');
}
});
},
}
}).
最佳答案
为了使用$scope[formName]
, Controller 必须位于表单元素上。通过直接定义:
<form name="theForm" ng-controller="TheCtrl">
或者作为指令:
directive("myDirective", function() {
return {
template: "<form name='theForm'>...</form>",
controller: ["$scope", function($scope) {
...
}],
...
};
});
如果满足以下条件之一,那么您必须为需要访问的每个元素定义名称属性:
<form name="theForm" ...>
<input name="theInput" ...>
然后您可以在相应的 Controller 内访问$setValidity()
,如上面所定义:
$scope.theForm.theInput.$setValidity(false);
再次记住:为了让 Controller 访问表单,它必须与表单位于同一元素,或者可能位于子范围。
关于angularjs - 对当前范围之外的元素使用 $setValidity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19225312/