如何在AngularJS中使用自定义模式等待用户交互

时间:2015-06-17 16:00:45

标签: javascript angularjs

我有这个自定义模式

<div>
    <script type="text/ng-template" id="confirmModal.html">
        <div class="modal-body">
            <span ng-bind="text"></span>
        </div>
        <div class="modal-footer">
            <button class="btn primary-btn btn2" ng-click="delete()">Delete</button>
            <button class="btn primary-btn btn2" ng-click="cancel()">Cancel</button>
        </div>
    </script>
</div>

我通过

访问
$scope.confirm = function(text) {

    $modal.open({
        templateUrl: 'confirmModal.html',
        backdrop: false,
        windowClass: 'infoModal',
        controller: function ($scope, $modalInstance) {
            $scope.text = text;

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

            $scope.delete= function () {
                $modalInstance.dismiss();
                return true;
            }
        }
    });
}

我这样调用它:

$scope.deleteFoo = function () {

     var r = $higherScope.confirm("Are you sure?");

     if(r) { /*code to delete foo*/ }
}

现在您可以想象,用户的互动并未触及r,因为代码不会等待用户继续与模式进行互动。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

如果用户点击带有confirm参数的删除触发器回调函数

,您需要向true添加回调函数以及需要调用此回调的按钮点击
$scope.confirm = function(text, callback) {
    $modal.open({
        templateUrl: 'confirmModal.html',
        backdrop: false,
        windowClass: 'infoModal',
        controller: function ($scope, $modalInstance) {
            $scope.text = text;
            $scope.cancel = function () {
                callback(false);
                $modalInstance.dismiss();

                return false;
            }

            $scope.delete= function () {
                callback(true);
                $modalInstance.dismiss();
                return true;
            }
        }
    });
}

定义您的回调函数whit one parameter

$scope.deleteFooCallback = function (isConfirmed) {
     if(isConfirmed) { /*code to delete foo*/ }
}

将该回调函数传递给confirm函数

$scope.deleteFoo = function () {
     var r = $higherScope.confirm("Are you sure?", $scope.deleteFooCallback);
}