在ng-click上打开模态时,$ scope会丢失

时间:2016-03-08 17:09:59

标签: javascript angularjs

当我尝试在ng-click上打开模态时,scipe变量会丢失。

var modalInstance = $modal.open({
 templateUrl: 'partials/create.html', 
 controller: 'AppCreateCtrl', 
 scope: $scope // <-- I added this 
});

1 个答案:

答案 0 :(得分:2)

您应该使用resolve属性传递数据,如下所示:

var modalInstance = $modal.open({
            templateUrl: templateSrv.templateUrl('partials/create.html'),
            controller: modalBootstrap,
            backdrop: 'static',
            keyboard: false,
            resolve: {
                data: function () {
                    var result = {};
                    result.scope = $scope;
                    return result;
                }
            }
        });

modalInstance.result.then(
            function (dataPassedFromModalConroller) {
                //this is called when the modal is closed
            },
            function (dataPassedFromModalConroller) { //Dismiss
              //this is called when the modal is dismissed
            }
        );

像这样指定模态实例的控制器(我们在另一个文件中执行此操作):

var modalBootstrap= function ($scope, $modalInstance, data) {
    $scope.modalInstance = $modalInstance;
    $scope.scope = data.userId;
};
modalBootstrap['$inject'] = ['$scope', '$modalInstance', 'data'];

你的模态模板看起来像这样:

<div ng-controller="AppCreateCtrl">modal content here</div>