[英]How do I pass a variable from directive to a controller using Angular
I have a function that is called in a directive html. 我有一个在指令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 wpGroup.html
<button ng-click="hideGroup(item.id)">-</button>
wp-group.js WP-group.js
scope:{hideGroup: &} //nothing else related to hideGroup or item.id
wp-view.html 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. javascript中的
functions
是一流的,您可以在任意位置将它们作为参数传递。
if i understand correctly you want to pass that hideGroup
function to a different controller and invoke it. 如果我正确理解,您想将该
hideGroup
函数传递给另一个控制器并调用它。
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. 我正在回答这个问题,希望
data-wp-group
是您的指令。
These should be modified, 这些应该修改,
wp-group.js WP-group.js
scope:{dataHideGroup: &} //nothing else related to hideGroup or item.id
inside up-group.js, 在up-group.js中,
scope.hideGroup = function(id){
scope.dataHideGroup({"id":id});
}
wp-view.html WP-view.html
<data-wp-group data-item="childItem" data-hide-group="vm.hideGroup(id)"/>
Hope you understand what I said 希望你明白我说的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.