簡體   English   中英

如何在angularJS中獲得對指令對象實例的引用?

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

所以基本上我有一個包裝了jquery插件(如果重要的話jsTree)的指令。 我想要的只是獲取指令對象的一種方法,這樣我就可以使用暴露的插件對象並進行一些修改,而無需在指令中真正構建功能。

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

我可以很好地實現自己的注冊表機制,並將其添加到每個指令的映射中,但是有沒有更簡單的方法,例如可能提供一個id並訪問它。 諸如dojo擁有dijit.byId或jquery插件如何通過dom進行訪問的方式(很奇怪,但是可以工作!)。

它不能通過設計來完成。 您不應該嘗試直接獲取指令對象。

相反,需要指令並在鏈接功能中訪問其控制器(這是指令進行通信的一種方式)。

例如:

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

腳本

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