【问题标题】:Asynchronous request and loading button with AngularJSAngularJS 的异步请求和加载按钮
【发布时间】:2013-10-03 04:34:15
【问题描述】:

Angular 控制器中的 DOM 操作似乎是错误的。但这并非没有一些令人头疼的事情:)

我有一个按钮,在 ng-click 时,它将在后台执行异步请求。在该异步请求期间,我希望禁用所有按钮(可能还有页面上的更多元素),并希望单击的按钮播放加载图标。

这样做最干净的方法是什么?

【问题讨论】:

标签: angularjs asynchronous angularjs-directive angularjs-scope


【解决方案1】:

我通常使用 $scope 上的一个名为 loading 的变量来执行此操作。每当发生异步操作时,只需将其设置为 true。然后任何需要被禁用或以其他方式受到影响的东西都可以以此为基础。

这是一个虚拟控件:

function TestCtrl($scope, $http) {
    $scope.loading = false;

    $scope.doASynch = function () {
        $scope.loading = true;
        $http.get("/url").success(function () {
            $scope.loading = false;
        });
    }
}

这是一个示例模板。

<div ng-controller="TestCtrl">
    <a class="button" ng-disabled="loading" ng-click="doASynch()">
        <span ng-hide="loading">Click me!</span>
        <span ng-show="loading">Loading....</span>
    </a>
</div>

【讨论】:

  • 我也有同样的想法,但我有点担心如何让它看起来真的很好。我认为这绝对是它的基础,但是我想添加一个动画,也许是为了让其他按钮淡出。如果我想应用 jQuery 效果,我该怎么做?你有什么想法吗?
  • @JordyMeow 您可以在接受 Mike 的回答后将其作为下一个 SO 问题发布;)
  • 好吧,我稍后会发布这个问题:) 我现在正在尝试自己创建一个指令,但我也想知道大家会怎么做。谢谢!
【解决方案2】:

这正是你要找的东西

Loading animations with Asynchronous HTTP Requests in Angular JS

    var app = angular.module('myapp', ["ui.utils", "ui.router"]);

    app.factory('iTunesData', function($http) {
       return {
            doSearch: function(sQuery) {
                 //return the promise directly.
                 return $http.jsonp('http://itunes.apple.com/search', {
                        params: {
                            "callback": "JSON_CALLBACK",
                            "term": sQuery
                        }
                    });
            }
       }
    });

    app.controller('iTunesSearch', function($scope, $location, $routeParams, iTunesData) {
        $scope.search = function() {
          iTunesData2.doSearch($scope.searchTerm)
            .then(function(result) {
                  $scope.data = result.data;
                  $location.path($scope.searchTerm);
              });
        }
        $scope.searchTerm = $location.$$path.split("/")[1];
        if($scope.searchTerm!="") {
          $scope.search();
        }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多