javascript - AngularJS 指令 - 指定回调的默认值

标签 javascript angularjs angularjs-directive callback default

我有一个指令接受一些方法作为回调。所有这些都需要属性才能工作。

scope: {
    onEventOne: '&?',
    onEventTwo: '&?'
}

function someWork() {
    onEventOne()(myVar);
    onEventTwo()(myOtherVar);
}

我的问题是当我没有定义其中一些回调时,因为它们并非都是必需的。

<div>
    <myDirective on-event-one="customHandler"></myDirective>
</div>

在上面的代码中,当调用 onEventOne()(myVar); 时一切正常,但是当调用 onEventTwo()(myOtherVar); 时我得到 TypeError : undefined 不是函数。 我尝试使用链接函数将空白函数设置为默认值,

function linkFunction(scope, element, attrs) {
    if (!attrs.onEventOne) {scope.onEventOne = scope.blankHandler;}
    if (!attrs.onEventTwo) {scope.onEventTwo = scope.blankHandler;}
}

但这会导致调用默认函数,同时仍然抛出 TypeError: undefined is not a function

如何设置这些默认功能?

最佳答案

函数的使用意味着 blankHandler 必须返回一个“空白”函数(angular.noop 在这里很方便)。在您的情况下,这就是我在链接功能中要做的:

var blankHandler = function() {
    return angular.noop;
};

if (!attrs.onEventOne) {scope.onEventOne = blankHandler;}
if (!attrs.onEventTwo) {scope.onEventTwo = blankHandler;}

scope.onEventOne()(myVar);
scope.onEventTwo()(myOtherVar);

关于javascript - AngularJS 指令 - 指定回调的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28584504/

相关文章:

javascript 禁用/启用输入文本表单

python - Django Rest Framework Angulars 使用 ModelSerializer 上传文件

javascript - 如何将 Quickblox 与 angularjs 集成?

javascript - 找不到指令 'ngSwitch' 所需的 AngularJS Controller 'ngSwitchWhen'

javascript - 如何在 AngularJS 中打开 .exe 文件?

angularjs - 使用 templateUrl 时,isolateScope() 返回未定义

javascript - 将顶部/左侧偏移坐标转换为日期/时间

javascript - AngularJS:如何使内部div可见

javascript - css 如何制作文本,使其从相同的 "column"开始(图片解释)

javascript - AngularJS - 将函数调用到组件中