【问题标题】:Passing a callback between directives in Angularjs在Angularjs中的指令之间传递回调
【发布时间】:2019-03-22 18:23:08
【问题描述】:

当仅从页面模板(使用控制器)传递回调时,this answer 正确解释了如何在指令模板中将回调的使用格式化为 JSON 对象,如下所示:

<a data-ng-click="callback({image: url})"></a>

但是如果指令只是将回调传递给另一个指令会发生什么。
它是否应该像这样传递回调:

<another-directive data-ng-click="callback()"></another-directive>

或者它应该像这样传递相同的对象格式:

<another-directive data-ng-click="callback({image: url})"></another-directive>

或者其他选择?
现在这些都不适合我。

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    我想我理解你想要完成的事情,所以我举个例子。

    您有一个控制器 (myController),它调用一个指令 (myDirective),该指令调用另一个指令 (anotherDirective),并且您想从 myControllermyDirective 向下传递一个“回调”函数到anotherDirective。以下是你可以做到的:

    angular
      .module('myApp', [])
      .controller('myController', ['$scope', function($scope) {
        $scope.foo = function(param) {
          alert('This function is declared on the main controller but called from a directive a few levels deep.  Parameter: ' + param);
        };
      }])
      .directive('myDirective', function() {
        return {
          template: `
            <h1>My Directive</h1>
            <another-directive callback="myFunction(b)"></another-directive>
          `,
          scope: {
            myFunction: '&'
          }
        }
      })
      .directive('anotherDirective', function() {
        return {
          template: `
            <h2>Another Directive</h2>
            <button data-ng-click="callback({b: {a: 'hello world'}})">Click Me</button>
          `,
          scope: {
            callback: '&'
          }
        }
      });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="myController">
      <my-directive my-function="foo(a)"></my-directive>
    <div>

    关键从最低级别的指令anotherDirective开始:

    <button data-ng-click="callback({b: {a: 'hello world'}})">Click Me</button>
    

    现在请记住 callback 是如何在其父级上设置的:

    <another-directive callback="myFunction(b)"></another-directive>
    

    以及myFunction 最初是如何在其父级上声明的:

    <my-directive my-function="foo(a)"></my-directive>
    

    我正在努力想一种方法来正确解释它,但是通过这个示例,您应该能够看到表达式如何冒泡到每个父级的模式。

    【讨论】:

    • 很高兴能帮上忙!
    猜你喜欢
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    相关资源
    最近更新 更多