angularjs - 为什么我不能在 angularjs 中要求 ngSubmit
问题描述
我有一个 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
解决方案
这是因为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);
}
}
});
};
}
};
}
推荐阅读
- android-studio - adb.exe 已停止使用 Android Studio 4.3.1 和 Android 9.+
- javascript - 在 POST 方法中通过 ajax call() 将参数传递给 api
- ios - 在 SwiftUI 的自定义视图中访问图像的修饰符
- c++ - 使用 Qt 应用程序在 iOS 上以后台模式获取 GPS 数据
- fortran - fortran 中的数据语句
- matlab - 如何使用符号工具箱将用户创建的函数从 GUI 转换为接受参数的 matlab 函数
- laravel - Laravel:发送电子邮件:错误(加载cafile流失败)
- javascript - TypeScript:类型 A 的索引键和类型 B 的保留键
- javascript - 使用 Javascript 从任何网站表单存储输入数据并将其发送到 webhook
- java - 为什么异步任务中的 ExecutorCompletionService 中的 take().get() 需要花费大量时间才能从其第一个完成的线程中获取结果?