angularjs - 对当前范围之外的元素使用 $setValidity

标签 angularjs angularjs-directive angularjs-scope angularjs-forms

我有一个全局指令,负责从 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/

相关文章:

javascript - 如何手动编译指令?

javascript - 如果我们使用 $http 获取数据,数据不会从一个自定义指令传输到另一个自定义指令

javascript - 如何根据条件改变背景颜色

angularjs - Angular - 错误 : $rootScope:infdig when setting a directive attribute using a controller variable

javascript - Angular Directive(指令)和同位素

javascript - 在 View 中保存表单数据

javascript - 如何在 Angular Js 中使用变量更改页面标题?

java - 带有自定义 AngularJS 登录页面的 Spring Boot 和安全性

javascript - 需要 12 小时格式而不显示 AM/PM Timepicker

javascript - Angular - 无法使用 ng-submit 获取选定的 ng-repeated 单选按钮