Angularjs 1x 将函数传递给 AngularJS 指令

Angularjs 1x Passing Functions to AngularJS Directives

我正在为 AngularJs 1.6.4 创建一个指令,试图完成以下任务:

<my-tag exec="console.log('Exec from tag')"/>
<my-tag/>

在第一种情况下,用户指定了 exec 参数,因此,在指令 link 中,我想调用它。

第二种情况,用户没有指定exec,所以,我想给元素绑定一个新函数。

两种方式,exec 函数都将在 ('click') 上调用。

我已经完成了这段代码:

directive

scope: {
    exec: '='
},

link: function(scope, element, attrs) {
    var doClick = function (ev) {
        ev.preventDefault();
        ev.stopPropagation();
        console.log('Exec was not there');
    };

    element.on('click', scope.exec ? scope.exec : self.doClick);
}

如果我单击带有 exec 参数的标签,则没有任何反应。如果我点击另一个标签,它就会工作。 有什么想法吗??

谢谢 问候。

您应该使用 & 而不是 =。您需要一个函数,而不是双向绑定。请参阅有关范围的 $compile 文档, 这里:$compile documentation

请注意,当使用 & 时,您将始终获得一个 exec 函数,无论您的指令的用户是否提供了一个。您可以通过检查 attrs.

来检查用户是否提供了 exec

这是一个例子。

(function(angular) {
  'use strict';

  angular
    .module('Test', [])
    .controller('TestCtrl', [function() {
      const vm = this;

      vm.doStuff = () => console.log('HIT!');
    }])

    .directive('myDir', [function() {
      return {
        scope: {
          exec : '&'
        },
        link: function(scope, ele, attrs) {
          // Here's how you call the passed in function.  It will always
          // be a function regardless of whether or not the user supplied
          // one.
          scope.exec();

          // Here's how to check if "exec" was user supplied.
          if (attrs.hasOwnProperty('exec'))
            console.log('User provided.');
        }
      };
    }]);
})(window.angular);

其中 HTML 看起来像这样:

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script data-require="angular.js@1.6.6" data-semver="1.6.6" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-app="Test" ng-controller="TestCtrl as vm">
    <my-dir exec="vm.doStuff()"></my-dir>
  </body>

</html>

工作中的笨蛋,这里:https://plnkr.co/edit/K3FZzll0pzOHL51BZ1Bs?p=preview