问题描述
我有一个带有注册表单的模态.相同的表单应显示在登录页面的底部,而不是在模式中.
I've got a modal with a registration form. The same form should be displayed at the bottom of the landing page not in a modal.
目前,我处理注册模式的控制器将 $modalInstance
作为其参数之一,沿着 $scope
等.如果我添加 ng-controller="SignUpCtrl"
到登陆页面中的一个元素,它不起作用,因为控制器不是通过 $modal.open
方法创建的,所以 Angular 抱怨 Unknown provider: $modalInstanceProvider .
Currently my controller that handles registration modal takes
$modalInstance
as one of its parameters along $scope
etc. If I add ng-controller="SignUpCtrl"
to an element in the landing page, it doesn't work, because the controller wasn't created via $modal.open
method and so Angular complains about Unknown provider: $modalInstanceProvider <- $modalInstance
.
我有一个用于注册用户的服务 (
authService.signUp(data).then/catch...)
,但控制器本身做了更多的工作 - 处理输入,发出事件(例如带有翻译的错误消息)、设置 cookie 等.
I've got a service for registering users (
authService.signUp(data).then/catch...)
, but the controller itself does a bit more - handles input, emits events (e.g. with translated error messages), sets cookies etc.
在不复制几乎整个控制器代码的情况下处理这种情况的最佳方法是什么?我应该将代码从控制器移到另一个更高级别的服务中吗?
What's the best way to handle such case without duplicating almost whole controller code? Should I move the code from controller into yet another, higher-level service?
推荐答案
在挣扎了很长时间后,我发现了一个更简单的技巧,可以在模态和正常情况下重用我们的控制器.
After struggling for a long while I found a easier trick to reuse our Controller for both modal and normal case.
我发现我们可以将调用者的范围传递给模态控制器,所以我将 modalInstance 推入 $scope 并将其传递给模态控制器.现在您没有未知的提供者问题,因为 $scope 是一个众所周知的问题.
I found that we can pass caller's scope to modal controller, so I pushed modalInstance into $scope and passed it to the modal controller.Now you don't have unknown provider problem because $scope is a well known one.
下面是一个例子:
CallerController = function($rootScope, ...) {
var modalScope = $rootScope.$new();
modalScope.modalInstance = $modal.open({
templateUrl: tempUrl,
controller: ReusableModalController,
scope: modalScope // <- This is it!
});
modalScope.modalInstance.result.then(function (result) {
// Closed
}, function () {
// Dismissed
});
};
ReusableModalController = function($scope, ...){
var dataToSendBack = 'Hello World';
$scope.modalInstance.close(dataToSendBack);
};
干杯!
这篇关于如何在 Angular UI Bootstrap 中为模态和非模态表单使用相同的控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!