javascript - Exposing angular directive function to another module -
suppose have module directive follows (this rough not tested) need implement 3 basic things
- configuration element appear
- event listeners base controller can use
- public methods base controller can call
angular.module("componentmodule",[]) .directive("mycomp",function(){
return{ replace:true, template:'<h2>this component</h2>', scope:{config= "@"}, link:function(scope,element,attr){ this.deleteelement = function(id){ //writing code delete component //this api function user can call delete } if (!scope.config.visible){ //this configuration object element this.visible(false)} } } }) then have base html containing directive call below
<div mycomm="first" config="eleconfig"></mycomp> <div mycomm="second" config="neweleconfig"></mycomp> i have separate controller base html follows,
angular.module("baseapp",['componentmodule']) .controller('basectrl',function(){ $scope.eleconfig = { visible:true, delete:function(e){ //this called if call delete method } } //this how delete method called $scope.first.deleteelement(); }) question how call deleteelement() method in basectrl shown above (want same way kendo ui does)
the pattern angular uses expose directive api scope. how ng-model , ng-form both expose ngmodelcontroller , ngformcontroller apis.
here how it:
angular.module("componentmodule",[]) .directive("mycomp",function($parse){ return{ replace:true, scope: { config: '&' }, template:'<h2>this component</h2>', controller: function($scope) { //directive api functions should added directive controller here or in link function (if need dom manipulation) }, link:function(scope,element, attr, ctrl){ //add directive controller if(scope.config().visible) { //element should visible, etc. } ctrl.deleteelement = function(){ //if function called want call config.delete method: if(scope.config && scope.config.delete) { //calling scope.config() method returns config object parent scope.config().delete(element); } } if(attr.mycomp) { //change scope.$parent scope.$parent[attr.mycomp] = ctrl; } } } }) assuming markup of:
<div my-comp="first" config="configobject"></div> <div my-comp="second" config="configobject"></div> in base controller
$scope.first.deleteelement(); or
$scope.second.deleteelement(); would delete appropriate element.
update:
i've updated directive based on updated question. want pass config object directive. best way & binding. if use & binding, need remember directive create new scope, , have attach controller $scope.$parent.
Comments
Post a Comment