代码之家  ›  专栏  ›  技术社区  ›  Yore

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

  •  0
  • Yore  · 技术社区  · 7 年前

    我正在为AngularJs 1.6.4创建一个指令,试图实现以下目标:

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

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

    在第二种情况下,用户没有指定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参数的标记,则不会发生任何事情。如果我单击另一个标记,它就会工作。 有什么想法吗??

    谢谢 当做

    1 回复  |  直到 7 年前
        1
  •  2
  •   benbotto    7 年前

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

    请注意,使用时 & 你总会得到 exec 函数,无论指令的用户是否提供了函数。您可以检查用户是否提供了 执行董事 通过检查 attrs .

    这里有一个例子。

    (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>
    

    工作plunk,此处: https://plnkr.co/edit/K3FZzll0pzOHL51BZ1Bs?p=preview