将obj从指令传递给AngularJS中的控制器 [英] Pass obj from directive to controller in AngularJS
问题描述
我正在尝试编写一个获取父控制器和父窗体控制器的指令,并将它们作为单个对象传递给我的控制器,这就是我所拥有的:
I'm trying to write a directive that get the parent controller and parent form controller and pass them as a single object to my controller, this is what I have:
HTML:
<div ng-controller="ParentController as self" ng-form="ParentForm">
<div ng-controller="ChildController1 as self" my-parent="self.parent">
ChildController1 parent:<br/>
{{self.parent}}
</div>
<br/>
<div ng-controller="ChildController2 as self" my-parent="self.parent">
ChildController2 parent:<br/>
{{self.parent}}
</div>
</div>
JS:
myApp.directive('myParent', function() {
var directive = {
restrict: 'A',
link: link
};
return directive;
function link(scope, element, attrs) {
var parentElement = element.parent();
var parentCtrl = parentElement.controller();
var formCtrl = parentElement.controller('form');
var parent = parentCtrl;
parent.form = formCtrl;
console.log("directive parent obj: ", parent);
// How can I pass the parent obj to controller???
}
});
我在这里写了一个更好的解释情况: https://plnkr.co/edit/axnR6t2Q82IVtzftq7y7?p=preview
I've wrote a plunker here to better explain the situation: https://plnkr.co/edit/axnR6t2Q82IVtzftq7y7?p=preview
我知道在这种情况下我可以在控制器中使用具有不同名称的controllerAs,但我需要使用指令(restrict:A指令)。
I know that in this case I could use controllerAs with different names in my controllers, but I need to make it work with a directive ("restrict: A" directive).
有人可以帮我解决这个问题吗?
Can someone please help me with this problem?
推荐答案
如果你没有为指令声明自己的范围,那么指令范围是与控制器范围相同,因此控制器和指令可以访问相同的范围数据。如果您需要在从指令启动的控制器中执行某些操作,那么在控制器监视范围变量中使用 $ scope.watch
。
If You not declare own scope for directive then directive scope is the same as controller scope, so controller and directive can access the same scope data. If You need to do something in controller launched from directive then in controller watch scope variable using $scope.watch
.
如果您需要将变量从一个组件传递到另一个组件(控制器到指令,反之亦然),请使用服务。 getter和setter的示例服务:
If You need pass variable from one component to another ( controller to directive or vice versa ) use services. Example service with getter and setter:
app.service("myService",function(){
this.data;
this.setData=function(val){
this.data=val;
};
this.getData=function(val){
return this.data;
};
});
在控制器中添加服务并使用 setData
,并将其添加到指令并调用 getData
。
Add service in controller and use setData
, and add it to directive and call getData
.
示例控制器代码:
myService.setData(this.form);
示例指令
var form=myService.getData();
这篇关于将obj从指令传递给AngularJS中的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!