简体   繁体   English

如何在angularJS中获得对指令对象实例的引用?

[英]how do you get a reference to the directive object instance in angularJS?

So basically I have a directive which wraps a jquery plugin (jsTree if that matters). 所以基本上我有一个包装了jquery插件(如果重要的话jsTree)的指令。 All i want is just a way to get the directive object so that I can use the exposed plugin object and do some modifications without really building a func into my directive. 我想要的只是获取指令对象的一种方法,这样我就可以使用暴露的插件对象并进行一些修改,而无需在指令中真正构建功能。

 var ngJSTree = angular.module('jsTree.directive', []); ngJSTree.directive('jsTree', ['$http', function($http) { var treeDir = { restrict: 'EA', fetchResource: function(url, cb) { return $http.get(url).then(function(data) { if (cb) cb(data.data); }); }, . . . init: function(s, e, a, config) { treeDir.managePlugins(s, e, a, config); this.tree = $(e).jstree(config); treeDir.manageEvents(s, e, a); } }; return treeDir; } ]); 

I could very well just implement a registry mechanism of my own and add it to map for each directive , but is there a simpler way like possibly giving an id and accessing it . 我可以很好地实现自己的注册表机制,并将其添加到每个指令的映射中,但是有没有更简单的方法,例如可能提供一个id并访问它。 Something like how dojo had dijit.byId or like how jquery plugins give you access through the dom (Weird but works !!!) . 诸如dojo拥有dijit.byId或jquery插件如何通过dom进行访问的方式(很奇怪,但是可以工作!)。

It cannot be done by design. 它不能通过设计来完成。 You shouldn't be trying to get the directive object directly. 您不应该尝试直接获取指令对象。

Instead, require the directive and access its controller in the link function (this is one way that directives communicate). 相反,需要指令并在链接功能中访问其控制器(这是指令进行通信的一种方式)。

For example: 例如:

<div directive1>
      <div directive2>
      </div>
</div>

Script 脚本

app.directive('directive1', function() {
    return {
        restrict: 'A',
        controller: function firstCtrl($scope) {
            ...
        }
    }
});

app.directive('directive2', function() {
    return {
        restrict: 'A',
        require: '^directive1',
        link: function(scope, element, attr, firstCtrl) {
            ... use firstCtrl ...
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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