从角带模态返回数据

时间:2015-11-04 16:05:04

标签: angularjs angular-ui angular-strap

我很抱歉,如果已经问过这个问题,但是是否可以从angular strap modal返回数据,如果有的话,是否有人可以提供短代码片段如何做?

从angular-ui模态返回数据有一个非常好的选择,但我无法找到带状方式。 非常感谢您的回答。

2 个答案:

答案 0 :(得分:3)

您可以非常轻松地从angular-strap模式返回任何数据。

假设你有一些对象,应该在模态提交后更新。例如,你有一个控制器,弹出你的模态。您所要做的就是定义一些处理程序,它应该更新您的数据,通过resolve选项将此处理程序传递给youp模式,并在模态控制器中调用此处理程序。

例:
该控制器包含用户详细信息并显示用于更改此数据的模式。

app.controller('userDetailsCtrl', ['$scope', '$modal', function($scope, $modal) {
    $scope.userDetails = {
        firstName: 'John',
        lastName: 'Smith'
    };

    $scope.showChangeUserDetailsModal = function() {
        var options = {
            userDetails: angular.copy($scope.userDetails),
            submit: function(result) {
                $scope.userDetails = angular.copy(result);
            }
        };
        $modal({
            controller: 'changeUserDetailsCtrl',
            contentTemplate: '', //Here is your template with some input fields
            show: true,
            resolve: {
                options: function() {
                    return options;
                }
            }
        });
    };
}]);

Modal的控制器调用处理程序submit,传递模态工作的结果。

app.controller('changeUserDetailsCtrl', ['$scope', 'options', function($scope, options) {
    $scope.userDetailsDraft = options.userDetails;

    $scope.submitChanges = function() {
        options.submit($scope.userDetailsDraft);
        $scope.$hide(); //Close modal after submit
    };
}]);

答案 1 :(得分:0)

我提出了一种简单的方法来实现这一点,API就像angular-ui模式一样。

您装饰$modal服务:

.config(['$provide', function($provide) {

    $provide.decorator('$modal', ['$q', '$rootScope', '$delegate', function ($q, $rootScope, $delegate)
    {
        return function returnAResultWhenClosingTheModal(options)
        {
            var deferred = $q.defer();

            if (!options.scope) {
                options.scope = $rootScope.$new();
            }

            options.scope.$close = function(result)
            {
                deferred.resolve(result);
                this.$hide();
            };

            // Call the real $modal service to create the modal
            var modal = $delegate(options);

            modal.result = deferred.promise;

            return modal;
        }
    }
    ]);
}])

创建模态与以往一样,除非现在每个模态都有一个result属性,这是一个在模态关闭时得到解析的承诺:

var myModal = $modal(modalOptions);

myModal.result.then(function(result)
{
    // I now have access to the result the modal closed with.
});

在模态控制器中,您只需使用要返回的结果调用$close上的新$scope方法:

// In the controller
$scope.$close(resultToReturn);