[英]How to pass data from inner controller of modal to outer controller in AngularJs
I'm trying to manipulate data inside a modal in AngularJS and after that, view it outside of the modal. 我试图在AngularJS中的模态内操作数据,然后在模态外查看数据。 So I have to pass the data from the inner controller (which is used by the modal) to the outer controller.
因此,我必须将数据从内部控制器(由模态使用)传递到外部控制器。 To put the data into the inner controller from the outer one I've done this with help of the option
resolve
of $modal.open
: 为了将数据从外部控制器放到内部控制器中,我借助
$modal.open
的选项resolve
做到了这$modal.open
:
myApp.controller('MyCtrl', function ($scope, $modal) {
$scope.number = 1;
$scope.openModal = function () {
$modal.open({
templateUrl: 'myModalContent.html',
backdrop: true,
windowClass: 'modal',
controller: function ($scope, $modalInstance, number) {
$scope.number = number;
$scope.submit = function () {
//How to iterate var number in the outer controller?
//$scope.number++;
$modalInstance.dismiss('cancel');
}
},
resolve: {
number: function () {
return $scope.number;
}
}
});
};
});
Now I want to count number up in the modal and show it outside of the modal. 现在,我想在模态中向上计数并在模态之外显示它。
$scope.number
affects obviously just the number in the current controller, so how can I set the variable of the outer controller? $scope.number
显然只影响当前控制器中的数字,那么如何设置外部控制器的变量?
Your help would be appreciated. 您的帮助将不胜感激。
Try _scope = $scope; 尝试_scope = $ scope; to hold on reference to outside controller.
保持对外部控制器的引用。 And inside inner controller, use _scope.number++;
在内部控制器中,使用_scope.number ++; Working fiddle:
工作提琴:
"http://jsfiddle.net/5xop3wL9/5/"
I would save your data to a service so it can be passed between controllers. 我会将您的数据保存到服务,以便可以在控制器之间传递。
myApp.factory('modalDataService', function () {
var modalData = {};
return {
getData: function () {
return modalData;
},
setData: function (newModalData) {
modalData = newModalData;
},
resetData: function () {
modalData = {};
}
};
});
You can then access your data from your controllers by passing in the factory as a dependency and calling functions like this: 然后,您可以通过传入工厂作为依赖项并调用如下函数来从控制器访问数据:
modalDataService.getData();
modalDataService.setData(newModalData);
modalDataService.resetData();
You can add a reference to $scope
of outer controller and then increment the number
using the new reference. 您可以向外部控制器的
$scope
添加一个引用,然后使用新的引用增加number
。
...
$scope.number = 1;
$higherScope = $scope;
...
//Inside submit
$scope.submit = function () {
//How to iterate var number in the outer controller?
$higherScope.number++;
$modalInstance.dismiss('cancel');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.