如何从另一个指令调用一个指令的函数

时间:2017-01-04 07:01:15

标签: javascript angularjs

我有以下指令abc

module.directive("abc", [
  "notifier", "session", function(notifier, session) {
    return {
      restrict: "E",
      replace: true,
      scope: {
        buffer: "="
      },
      template: "<li class=\"file \" ng-class=\"{active: active, dirty: dirty, changed: changed}\">\n  " + 
"   <ul class=\"participants\">\n    " + 
"       <li ng-class=\"participant.style\" ng-repeat=\"(id, participant) in buffer.participants\" title=\"{{participant.handle}}\">\n    </li>\n  " + 
"   </ul>\n  " + 
"   <a class=\"filename\" ng-click=\"activateBuffer(buffer)\" ng-dblclick=\"promptFileRename(buffer) | trackEvent:'File':'Rename':'Sidebar'\">{{buffer.filename}}</a>\n  " + 
"   <ul class=\"file-ops\">\n    " + 
"       <li class=\"delete\">\n      " + 
"           <button ng-click=\"promptFileDelete(buffer) | trackEvent:'File':'Delete':'Sidebar'\" class=\"btn btn-mini\" tooltip=\"Delete this file\" tooltip-placement=\"right\">\n        " + 
"               <i class=\"icon-remove\"></i>\n      " + 
"           </button>\n    " + 
"       </li>\n  " + 
"   </ul>\n" + 
"</li>",

controller: function($scope){
        var buffer;
        buffer = $scope.buffer;

        $scope.$watch((function() {
          return session.isDirty(["buffers", buffer.id]);
        }), function(dirty) {
          $scope.dirty = dirty && Date.now();
          return $scope.changed = dirty && !$scope.active;
        });
        $scope.$watch((function() {
          return session.getActiveBuffer() === buffer;
        }), function(active) {
          $scope.active = active && Date.now();
          return $scope.changed = false;
        });
        $scope.activateBuffer = function(buffer) {
          return session.activateBuffer(buffer.filename);
        };
        $scope.promptFileRename = function(buffer) {
            console.log("rename file function called");
       /*   return notifier.prompt("Rename file", buffer.filename, {*/
        //confirm: function(filename) {
          //return session.renameBuffer(buffer.filename, filename);
        //}
      /*});*/
        };
        $scope.promptFileDelete = function(buffer) {
            console.log("delete file function called");
       /*   return notifier.confirm("Confirm Delete", "Are you sure that you would like to delete " + buffer.filename + "?", {*/
        //confirm: function() {
          //return session.removeBuffer(buffer.filename);
        //}
      /*});*/
        };

      //
      //link: function($scope, $el, attrs) {
//}

}

    };
  }
]);
来自另一个指令def

我试图调用abc中的函数 我已尝试requireabc指令引入def here

module.directive("def", [
  "$timeout", "$q", "session", "notifier", "visitor", "overlay", function($timeout, $q, session, notifier, visitor, overlay) {
    return {
      require: 'abc',  //<-- requiring the directive
      restrict: "E",
      replace: true,
      template: "<div class=\"plunker-sidebar\">\n  "
+ " <plunker-restorer></plunker-restorer>\n  "
+ " <div class=\"share\" ng-switch=\"session.isSaved()\">\n    "
+ "     <div ng-switch-when=\"true\" addthis-toolbox class=\"addthis_default_style addthis_20x20_style\" addthis-description=\"{{session.description}}\">\n  "
+ "         <a target=\"_self\" class=\"addthis_button_twitter\"></a>\n      "
+ "         <a target=\"_self\" class=\"addthis_button_facebook\"></a>\n      "
+ "         <a target=\"_self\" class=\"addthis_button_google_plusone_share\"></a>\n      "
+ "         <a target=\"_self\" class=\"addthis_button_linkedin\"></a>\n      "
+ "         <a target=\"_self\" class=\"addthis_button_compact\"></a>\n    "
+ "     </div>\n  "
+ " </div>\n  "
+ " <details open>\n"
+ "     <summary class=\"header\">Files</summary>\n    "
+ "     <ul class=\"plunker-filelist nav nav-list context-menu-one\">\n      "
+ "         <abc buffer=\"buffer\" ng-repeat=\"buffer in session.getBufferArray() | orderBy:'filename'\">\n      "
+ "                     </plunker-sidebar-file>\n      "
+ "         <li class=\"newfile\">\n        "
+ "             <a ng-click=\"promptFileAdd() | trackEvent:'File':'Add':'Sidebar'\">\n          "
+ "                 <i class=\"icon-file\"></i> New file\n        "
+ "             </a>\n      "
+ "         </li>\n    "
+ "     </ul>\n  "
+ " </details>\n  "
+ " <details ng-show=\"session.isSaved()\">\n    "
+ "     <summary class=\"header\">Versions "
+ "         <span class=\"label\" ng-bind=\"session.plunk.history.length | number\"></span>"
+ "     </summary>\n    "
+ "     <ul class=\"plunker-filelist nav nav-list\">\n      "
+ "         <li ng-class=\"{active: $index==session.currentRevisionIndex, frozen: $index==session.plunk.frozen_version}\" ng-repeat=\"event in session.plunk.history | orderBy:'-created_at'\">\n        "
+ "             <a ng-click=\"revertTo($index) | trackEvent:'Plunk':'Revert':'Sidebar'\">\n          "
+ "                 <i ng-class=\"event.event | eventIcon\"></i>\n          "
+ "                 <span ng-bind=\"event.event | eventName\"></span>\n          "
+ "                 <abbr timeago=\"{{event.created_at}}\"></abbr>\n          "
+ "                 <i class=\"icon-lock\" ng-show=\"session.plunk.frozen_at && $index==session.plunk.history.length - 1 - session.plunk.frozen_version\" tooltip=\"The plunk is currently frozen at this version\" tooltip-placement=\"right\"></i>\n        "
+ "             </a>\n      "
+ "         </li>\n    "
+ "     </ul>\n  "
+ " </details>\n  "
+ " <details open>\n    "
+ "     <summary class=\"header\">Plunk</summary>\n    "
+ "     <form>\n      "
+ "         <div>\n        "
+ "             <label for=\"plunk-description\">\n          "
+ "                 <div>Description:</div>\n          "
+ "                 <textarea id=\"plunk-description\" rows=\"2\" ng-model=\"session.description\"></textarea>\n        "
+ "             </label>\n        "
+ "             <label for=\"plunk-tags\">\n          "
+ "                 <div>Tags:</div>\n          "
+ "                 <plunker-tagger id=\"plunker-tags\" ng-model=\"session.tags\" />\n        "
+ "             </label>\n        "
+ "             <div ng-show=\"session.isSaved()\">\n          "
+ "                 <div>User:</div>\n          "
+ "                 <plunker-inline-user user=\"session.plunk.user\"></plunker-inline-user>\n        "
+ "             </div>\n        "
+ "             <div ng-hide=\"session.isSaved() || !visitor.isMember()\">\n          "
+ "                 <div>Privacy:</div>\n          "
+ "                 <label>\n            "
+ "                     <span tooltip=\"Only users who know the url of the plunk will be able to view it\" tooltip-placement=\"right\">\n  "
+ "                         <input type=\"checkbox\" ng-model=\"session.private\" />\n              private plunk\n            "
+ "                     </span>\n          "
+ "                 </label>\n        "
+ "             </div>\n        "
+ "             <div ng-show=\"session.isSaved()\">\n          "
+ "                 <div>Privacy:</div>\n          "
+ "                 <abbr ng-show=\"session.plunk.private\" tooltip-placement=\"right\" tooltip=\"Only users who know the url of the plunk will be able to view it\">"
+ "                     <i class=\"icon-lock\"></i> private plunk"
+ "                 </abbr>\n          "
+ "                 <abbr ng-hide=\"session.plunk.private\" tooltip-placement=\"right\" tooltip=\"Everyone can see this plunk\">"
+ "                     <i class=\"icon-unlock\"></i> public plunk"
+ "                 </abbr>\n        "
+ "             </div>\n      "
+ "         </div>\n    "
+ "     </form>\n  "
+ " </details>\n"
+ "</div>",
      link: function($scope, $el, attrs) {
        var $desc;
        $scope.session = session;
        $scope.visitor = visitor;

    jQuery.contextMenu({
        selector: '.context-menu-one',
        callback: function (key, options) {
          switch(key) {
            case "Rename":
              plunkerSidebarFile.promptFileRename();  // <- call to func
              break;
            case "Delete":
              plunkerSidebarFile.promptFileDelete(); // <-- call to func
              break;
          }
        },
        items: {
          "Rename": {name: "Edit", icon: "edit"},
          "Delete": {name: "Delete", icon: "delete"}
        }
    });

        $scope.promptFileAdd = function() {
          return notifier.prompt("New filename", "", {
            confirm: function(filename) {
              return session.addBuffer(filename, "", {
                activate: true
              });
            }
          });
        };
        $scope.revertTo = function(rel) {
          var revert;
          if (!session.isSaved()) {
            return;
          }
          revert = function() {
            return overlay.show("Reverting plunk", session.revertTo(rel));
          };
          if (session.isDirty()) {
            return notifier.confirm("You have unsaved changes that will be lost if you revert. Are you sure you would like to revert?", {
              confirm: revert
            });
          } else {
            return revert();
          }
        };        
        $desc = $el.find("#plunk-description");
        $desc.autosize({
          append: "\n"
        });
        $scope.$watch("session.description", function(description) {
          return $desc.trigger("autosize");
        });
        $scope.$on("resize", function() {
          return $desc.trigger("autosize");
        });
        return $(".share").on("click", function(e) {
          e.stopPropagation();
          return e.preventDefault();
        });
      }
    };
  }
]);

但我收到错误editor-0.11.9.js:5931 Error: No controller: abc

2 个答案:

答案 0 :(得分:0)

你不能随意使用&#34;要求&#34;获取控制器的实例。

如果在指定级别找到控制器/指令,则需要工作。

因此,例如,如果您的指令都存在于同一父节点中(例如,它们是在同一控制器的模板中定义的),那么您可以使用带有^^^前缀的require来指定angular可以找到相对于当前指令位置所需的控制器。

来自文档:

  

^^前缀表示此指令在其父项上搜索控制器。 (A ^前缀会使指令在其自己的元素或其父元素上查找控制器;没有任何前缀,该指令仅在其自己的元素上查找。)

因此,例如,如果您的指令位于具有以下模板的控制器中:

<div>
  <abc></abc>
  <def></def>
</div>

然后,您可以使用require: '^abc'将控制器添加到“&#39; def&#39;指示。请注意,它将在link函数中作为最后一个参数给出,因此您可以按如下方式访问它:

link: function($scope, $el, attrs, abcController) { ...

答案 1 :(得分:0)

说你有指令

        angular.module('app', [])
        .directive("Directve1", function() {
          return {
            restrict: "E",
            controller: function($scope) {

              this.sayHello = function() {
                //some logic...
              };
              ....
        });

另一个需要Directve1方法的指令

            .directive("Directve2", function() {
              return {
                require: "Directve1",  //include require
                link: function (scope, element, attrs, directive1Ctrl) {
                  directive1Ctrl.sayHello();
                }
              };
             })

注意:directive1Ctrl是require中提到的指令的控制器(require:“Directve1”)