如何将函数调用为另一个函数作为以字符串形式传递的参数

时间:2015-09-28 18:09:15

标签: javascript angularjs

我有一个服务功能我试图在控制器中调用。该服务还调用同一服务中的另一个功能。当我可以从控制器调用服务时,如果我明确传入第二个服务,我只能让它工作。我想要做的是能够传递一个调用第二个服务的字符串。它看起来更干净,更容易阅读。但我无法弄清楚如何做到这一点。

服务

function $cmCallOut($timeout, $cmAutoscroll) {

    var service = {
      runCallOut: runCallOut,
      unavailable: unavailable,
      destroy: destroy,
      create: create,
      update: update
    };
    return service;

    function runCallOut(recordId, callout) {
      // Wrap in timeout to wait for DOM to load before grabbing the element
      $timeout(function() {
        // Get element which to perform callout animation on
        var element = angular.element('[record-id=' + recordId + ']');
        // Get the elements coords so we can scroll to it
        var rect = element[0].getBoundingClientRect();
        // Scroll to element
        $cmAutoscroll.toTop(rect.top);
        // Run animation
        callout(element);
      });
    }

    function unavailable(element) {
      element.velocity('callout.shake');
    }

    function destroy(element) {
      element.velocity('transition.expandOut', {duration : 350});
    }

    function create(element) {
      element.css('display', 'none');
      element
      .velocity('transition.expandIn', {duration : 450, display: 'block', delay: 350})
      .velocity('callout.flash');
      $timeout(function() {
        element.css('transform', 'none');
      }, 2000);
    }

    function update(element) {
      element.velocity('callout.flash', {duration: 1500, delay: 350});
    }

  }

控制器:

$cmCallOut.runCallOut(chargeId, $cmCallOut.create);

想要这样称呼:

$cmCallOut.runCallOut(chargeId, 'create');

1 个答案:

答案 0 :(得分:3)

由于您想要的函数是您在顶部声明的服务变量的键,因此您可以像这样调用它:

service[callout](element);

因此...

function runCallOut(recordId, callout) {
  // Wrap in timeout to wait for DOM to load before grabbing the element
  $timeout(function() {
    // Get element which to perform callout animation on
    var element = angular.element('[record-id=' + recordId + ']');
    // Get the elements coords so we can scroll to it
    var rect = element[0].getBoundingClientRect();
    // Scroll to element
    $cmAutoscroll.toTop(rect.top);
    // Run by calling the function that is a key on service
    service[callout](element);
  });
}
相关问题