简体   繁体   中英

How do I pass a variable from directive to a controller using Angular

I have a function that is called in a directive html. I'd like to pass that object to the controller. How do I do that? Below is a copy of what I have so far

wpGroup.html

<button ng-click="hideGroup(item.id)">-</button>

wp-group.js

 scope:{hideGroup: &} //nothing else related to hideGroup or item.id

wp-view.html

 <data-wp-group data-item="childItem" data-hide-group="vm.hideGroup(vm.id)"/>

functions in javascript are first class, they can be pass as arguments wherever you want.

if i understand correctly you want to pass that hideGroup function to a different controller and invoke it.

You can share the reference between the two , with some events handling (or better) using custom service.

.service('ShareDataService', function(){
 var data;
 this.setFn = function(fn){
  data = fn;
 }
 this.getFn = function(){
  return data;
 }
})

then in your directive inject the service and set the data.

ShareDataService.setFn(scope.hideGroup);

and get the reference in your controller;

var hideGroupFn = ShareDataService.getFn();

I'm answering this question hoping that data-wp-group is your directive.

These should be modified,

wp-group.js

 scope:{dataHideGroup: &} //nothing else related to hideGroup or item.id

inside up-group.js,

scope.hideGroup = function(id){
  scope.dataHideGroup({"id":id});
 }

wp-view.html

 <data-wp-group data-item="childItem" data-hide-group="vm.hideGroup(id)"/>

Hope you understand what I said

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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