【问题标题】:Why I cannot require ngSubmit in angularjs为什么我不能在 angularjs 中要求 ngSubmit
【发布时间】:2019-06-25 05:52:47
【问题描述】:

我有一个 angularjs 指令,我需要在其中使用 ngSubmit:

.directive('testDirective', function(){
   return {
     scope: {},
     require: '?^ngSubmit',
     ....

在我的 html 中,我将 ng-submit 作为指令的父级:

<form name="testForm" ng-submit="printHello()">
  <test-directive></test-directive>
  <button type="submit">submit button</button>
</form>

我想知道为什么我无法访问它并且在链接函数中,ngSubmitCtrl 始终未定义:

link: function(scope, element, attr, ngSubmitCtrl){
  // ngSubmitCtrl is always undefind
}

这是具有完整代码的 plunker: https://next.plnkr.co/edit/8duvT6xHcixvbrDz?open=lib%2Fscript.js&deferRun=1

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    这是因为ngSubmit 没有实例化控制器。它与许多其他ngEventDirectives 一起批量创建,并且只定义了一个编译属性。看一下源码:

    https://github.com/angular/angular.js/blob/master/src/ng/directive/ngEventDirs.js

    forEach(
      'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
      function(eventName) {
        var directiveName = directiveNormalize('ng-' + eventName);
        ngEventDirectives[directiveName] = ['$parse', '$rootScope', '$exceptionHandler', function($parse, $rootScope, $exceptionHandler) {
          return createEventDirective($parse, $rootScope, $exceptionHandler, directiveName, eventName, forceAsyncEvents[eventName]);
        }];
      }
    );
    
    function createEventDirective($parse, $rootScope, $exceptionHandler, directiveName, eventName, forceAsync) {
      return {
        restrict: 'A',
        compile: function($element, attr) {
          // NOTE:
          // We expose the powerful `$event` object on the scope that provides access to the Window,
          // etc. This is OK, because expressions are not sandboxed any more (and the expression
          // sandbox was never meant to be a security feature anyway).
          var fn = $parse(attr[directiveName]);
          return function ngEventHandler(scope, element) {
            element.on(eventName, function(event) {
              var callback = function() {
                fn(scope, {$event: event});
              };
    
              if (!$rootScope.$$phase) {
                scope.$apply(callback);
              } else if (forceAsync) {
                scope.$evalAsync(callback);
              } else {
                try {
                  callback();
                } catch (error) {
                  $exceptionHandler(error);
                }
              }
            });
          };
        }
      };
    }
    

    【讨论】:

      猜你喜欢
      • 2022-06-17
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      相关资源
      最近更新 更多