【问题标题】:How to inject factory in angular boostrap modal's controller?如何在角度引导模态控制器中注入工厂?
【发布时间】:2015-05-18 11:08:35
【问题描述】:

我想创建对话框以确认提交按钮。所以我正在使用角度用户界面引导程序。

这是我的主控制器代码:

FrontEnd.controller('PostViewController',function($scope,$stateParams,PostFactory, $modal){

    $scope.openConfirm = function(size) {

            var modalInstance = $modal.open({
                animation: true,
                templateUrl: 'ConfirmDialog.html',
                controller: 'ConfirmDialogController',
                size: size, 
                resolve: {
                    form: function () {
                            return $scope.form;
                        },
                    //tried with this line as well, but could not resolve error
                    PostFactory: "PostFactory"   
                }
            });

            modalInstance.result.then(function (response) {
                $scope.isSurveySubmitted = true;
                $scope.message = response.message;

                //$scope.selected = selectedItem;
              }, function () {
                console.log('Modal dismissed at: ');
            });
    };
});

这是我的 ConfirmDialogController:

FrontEnd.controller('ConfirmDialogController', function($scope, $http, $modalInstance, form, PostFactory){

    $scope.ok = function () {

        PostFactory.SubmitSurvey(form).success(function(response){
            $modalInstance.close(response);
        }).success(function(response){
            $modalInstance.close(response);
        });
    };

    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
});

Modal 正确打开,没有错误。当我单击取消按钮时,它会按预期关闭模式。但是当我点击 Ok 时,它会调用 $scope.ok() 但在控制台中抛出错误并显示 PostFactory is undefined 消息。

那该怎么办?感谢您的帮助。

【问题讨论】:

  • 那么 PostFactory 的代码在哪里???错误很清楚,切中要害

标签: angularjs angular-ui-bootstrap


【解决方案1】:

我认为你可以在$modalInstance.open() 中使用scope 字段

将工厂设置为新作用域上的属性

var scope = $scope.$new();
scope.factory = PostFactory;
$modalInstance.open({
    // other stuff
    scope: scope
});

然后在youou modal的控制器中引用$scope.factory。

不确定它是否会搞砸其他事情,不过值得一试。

【讨论】:

  • 对此+1。您可以告诉 $modal 使用哪个范围,这样您就可以使用与父控制器中相同的 $scope
  • 或在 PostViewController $scope 上设置工厂,并将 { scope: $scope } 传递给 modalInstance。 [@Dan 说了什么]
  • 对不起。我的代码有效。它不起作用,因为我在解析语句中尝试使用 PostFactory: "PostFactory" 。因此,只需删除该声明,它就起作用了。顺便说一句,非常感谢你们给我更多关于如何将范围传递给模态的信息。干杯!
猜你喜欢
  • 2013-08-16
  • 1970-01-01
  • 2016-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
相关资源
最近更新 更多