How to call a method defined in an AngularJS directive?

前端 未结 13 1049
萌比男神i
萌比男神i 2020-11-22 14:39

I have a directive, here is the code :

.directive(\'map\', function() {
    return {
        restrict: \'E\',
        replace: true,
        template: \'<         


        
13条回答
  •  情歌与酒
    2020-11-22 15:31

    How to get a directive's controller in a page controller:

    1. write a custom directive to get the reference to the directive controller from the DOM element:

      angular.module('myApp')
          .directive('controller', controller);
      
      controller.$inject = ['$parse'];
      
      function controller($parse) {
          var directive = {
              restrict: 'A',
              link: linkFunction
          };
          return directive;
      
          function linkFunction(scope, el, attrs) {
              var directiveName = attrs.$normalize(el.prop("tagName").toLowerCase());
              var directiveController = el.controller(directiveName);
      
              var model = $parse(attrs.controller);
              model.assign(scope, directiveController);
          }
      }
      
    2. use it in the page controller's html:

      
      
    3. Use the directive controller in the page controller:

      vm.myDirectiveController.callSomeMethod();
      

    Note: the given solution works only for element directives' controllers (tag name is used to get the name of the wanted directive).

提交回复
热议问题