如何延迟单击事件,直到$http调用完成,页面内容准备好

how to delay a click event until a $http call is finished and page content is ready?

本文关键字:调用 准备好 http 直到 何延迟 延迟 事件 单击      更新时间:2023-09-26

我创建了一个使用$http调用获取其内容的模态。来自$http调用的数据量因帐户而异。所以,有时候模态还没有准备好如果用户点击按钮打开模态它会有一段时间什么都不会显示。

我想延迟click事件,直到模态的内容准备好。我的意思是,我希望模态在完全渲染时被打开。我尝试了$timeout服务,但它不是很好,因为一些帐户需要更多的时间,其中一些需要更少:

$('#modalLink').click(function(e) {
        e.preventDefault();
        $timeout(function() {
            $("#myModal").modal({
            persist: true,
            height: 'auto',
            maxWidth: 900,
            onClose: function (dialog) {
                $.modal.close();
             }
        });
        }, 500);
    });

那么我如何设置点击事件延迟,直到我的范围对象($scope.myArray)被定义?

简单的答案是在加载数据时在模态中显示一个旋转器。加载后,隐藏旋转器并显示数据。我宁愿那样做。

然而,如果你不想显示spinner,你可以用$http开始加载你的数据,并把你的模态的开头放在$http的.then()语句中。美元,http。Post等提供。

$('#modalLink').click(function(e) {
    e.preventDefault();
    $http.get(blablabla).then(fucntion(){
        //open your modal here
    };
});

请在这里阅读更多关于承诺的内容https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

注。我还建议您使用服务方法从服务器获取数据。

另外,请不要忘记使用。catch()方法捕获错误。

假设按钮为

<button ng-disabled="isDisabled">Button</button>

And in controller:

$scope.isDisabled = true;
$http.get('someUrl')
     .then(function(result){
     $scope.isDisabled = false;
})

这将确保按钮在页面加载时禁用,但在函数调用后启用。

你需要做的是,设置某种标志,当你的$http已经解决:

$http.get('/url')
    .then(function(res) {
        $scope.flag = true;
    });

现在,在模态或模态触发按钮上设置ng-show,使$scope.flag为真

或者更好的是,在Modal上设置一个加载GIF,只要flag为假,它就会显示自己。一旦你的承诺解决了,隐藏这个加载图标,并显示你的模态内容。

<div class="modal">
    <div class="overlay" ng-show="!flag"></div>
    <div class="modal-content" ng-show="flag"></div>
</div>

您也可以在类似的功能中禁用该按钮

尝试ui-bootstrap并在modal的解析中获取数据模态解析的工作原理与路由器解析

相同。

的例子:

$scope.openModal = $uibModal.open({ templateUrl: 'stackedModal.html', // you can use template option instead templateUrl size: 'sm', resolve: { items: function () { return //do something that you want. } } controller: function($scope, items) { //your data is in items injector. } });