【问题标题】:pass callback to directive - angularjs将回调传递给指令 - angularjs
【发布时间】:2015-08-31 06:04:00
【问题描述】:

我尝试通过指令向元素添加动画。动画完成后,我希望它调用传递的回调函数。我尝试以这种方式实现它 (SO - How to add validation attributes in an angularjs directive)

'addAnimation' 指令:

angular.module('myModule')
  .directive('addAnimation', function ($compile) {
    return {
      restrict: 'A',
      scope: {
        onFinish:"&"
      },
      replace: false,
      terminal: true,
      priority: 1000,
      link: function (scope, element, attrs) {
        element.on('click', function() {           
          $('.selector').animate({ ... }), function() {
            if(attrs.cb) {
              attrs.cb.onFinish();
            }
          });             
        })

        element.removeAttr("addAnimation"); //remove the attribute to avoid indefinite loop

        $compile(element)(scope);
      }
    };
  });

动画应该添加到的指令'aDirective':

angular.module('myModule')
  .directive('aDirective', function () {
    return {
      templateUrl: 'path/to/template.html',
      restrict: 'EA',
      link: function (scope, element, attrs) {
        scope.test = function() {
          console.log('this should be logged');
        }
      }
    };
  });


<div>
  <div add-animation cb="{onFinish: 'test'}"></div>
</div>

当我单击它时,动画开始,但随后出现错误:

Uncaught TypeError: attrs.cb.onFinish is not a function

记录attrs.cb 似乎没有解决该功能:

{onFinish: 'test'}

我在这里做错了什么?

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    你已经在指令的作用域上定义了onFinish,你应该像在作用域上一样使用它,它需要在元素中使用on-finish,所以而不是:

    attrs.cb.onFinish()
    

    scope.onFinish()
    

    另外,如果你这样定义:

    scope: {
        onFinish:"&"
    },
    

    你应该以这种方式将它传递给指令:

    <div add-animation on-finish="test()"></div>
    

    【讨论】:

    • 谢谢,它有效。只是 div 内的 onFinish 需要完成。我无法编辑它。
    猜你喜欢
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 2013-01-15
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    相关资源
    最近更新 更多