angularjs - 将回调传递给指令 - angularjs

标签 angularjs angularjs-directive

我尝试通过指令向元素添加动画。动画完成后,我希望它调用传递的回调函数。我尝试以这种方式实现它 ( 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'}

我在这里做错了什么?

最佳答案

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

attrs.cb.onFinish()

scope.onFinish()

另外,如果你这样定义它:

scope: {
    onFinish:"&"
},

您应该以这种方式将其传递到指令中:

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

关于angularjs - 将回调传递给指令 - angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30850320/

相关文章:

javascript - AngularJS HTTP GET 请求不起作用

javascript - 在HTML部分使用 "."访问对象并在JavaScript部分使用 "[]"?

javascript - 指令中的多个 $observe

javascript - 如何在 AngularJS 的元素指令模板内使用属性指令?

javascript - Controller 中未定义 Angular 工厂

jquery - 如何减去两个AngularJS日期变量

javascript - Angular Js 新手 - Controller View 中的链接触发另一个 Controller 操作

javascript - Angular Js 性能和加载时间

javascript - 在指令中,处理对用户定义的方法名称的调用

javascript - 在指令范围和 Controller $scope 之间共享数据?