[英]Injecting dependency in controller (not as argument)
I want to use controller in modal (ui.bootstrap) and as normal view (without modal). 我想在模式(ui.bootstrap)和普通视图(无模式)中使用控制器。 Controller is used for adding things - as normal view and in modal. 控制器用于添加事物-作为普通视图和模式。
To know if controller is used by modal or normal view I'm using resolve attr in modal: 要知道控制器是由模态视图还是普通视图使用,我在模态中使用resolve attr:
$modal.open({
resolve: {
inModal: function() {
return true;
}
}
//other
})
Problem is that to use it I need to inject it into controller: 问题是要使用它,我需要将其注入控制器:
function myCtrl($scope, inModal) {
$scope.inModal = inModal;
}
But this depency isn't available in normal view. 但是这种依赖性在普通视图中不可用。 Can I inject inModal
in controller if it is available? 如果可用,我可以在控制器中注入inModal
吗?
function myCtrl($scope) {
//$scope.inModal = inject inModal if it is available
}
Instead of resolve, you can pass a scope to your $modal options: 除了解析,您还可以将范围传递给$ modal选项:
$scope.inModal = true;
$modal.open({ scope: $scope });
Then in your controller: 然后在您的控制器中:
function myCtrl($scope) {
if($scope.inModal) {
...
}
}
When you pass $scope to $modal, the $modal will create a child scope that prototypically inherits inModal from the parent scope. 当您将$ scope传递给$ modal时,$ modal将创建一个子作用域,该子作用域典型地从父作用域继承inModal。 When the controller function is invoked in a normal view, inModal would not be defined. 在普通视图中调用控制器功能时,不会定义inModal。
You can inject it using $inject like this: 您可以使用$ inject注入它,如下所示:
myCtrl.$inject = ['$scope', 'inModal'];
I have done that and it is working fine. 我已经做到了,并且工作正常。 below is the code for the $modal. 以下是$ modal的代码。
$modal.open({
controller : "myCtrl",
resolve: {
inModal: function() {
return true;
}
}
})
controller: 控制器:
app.controller('myCtrl', function($scope, inModal) {
//you can directly use inModal or assign it to $scope property
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.