简体   繁体   中英

Angularjs 1x Passing Functions to AngularJS Directives

I'm creating a directive for AngularJs 1.6.4 trying to accomplish the following:

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

On the first case, the user specified the exec param, so, in the directive link, I want to invoke that.

On the second case, the user did not specify the exec, so, I want to bind a new function to the element.

Both ways, the exec function is to be called on('click').

I have done this code:

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);
}

Nothing is happening if I click the tag with the exec param. If I click the other tag, it is working. Any ideas ??

Thanks Regards.

You should be using & and not = . You want a function, not two-way binding. See the $compile documentation on scope, here: $compile documentation

Note that when using & you'll always get an exec function, whether or not the user of your directive supplied one. You can check if the user supplied exec by checking attrs .

Here's an example.

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

Where the HTML looks like this:

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

Working plunk, here: https://plnkr.co/edit/K3FZzll0pzOHL51BZ1Bs?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM