【问题标题】:AngularJS Directives - specify defaults for callbacksAngularJS 指令 - 指定回调的默认值
【发布时间】:2015-04-19 12:09:38
【问题描述】:

我有一个指令,它采用一些方法作为回调。它们都需要属性才能工作。

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

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

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

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

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

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

如何设置这些默认功能?

【问题讨论】:

    标签: javascript angularjs angularjs-directive callback default


    【解决方案1】:

    函数的使用意味着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);
    

    【讨论】:

      猜你喜欢
      • 2013-12-27
      • 2014-03-28
      • 1970-01-01
      • 2013-09-18
      • 2017-03-06
      • 2015-07-26
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      相关资源
      最近更新 更多