LoginSignup
1
1

More than 5 years have passed since last update.

[AngularJS] Promiseの状態をビューに表示する便利モジュール作りました

Last updated at Posted at 2015-12-03

Promiseの進捗によって表示を切り替える

app.js
.controller('FooController', function ($scope, $http) {
  $scope.save = function () {
    $scope.pending = true;
    $scope.message = '';
    $http.post('http://...').then(function () {
      $scope.pending = false;
      $scope.message = '保存しました';
    }, function () {
      $scope.pending = false;
      $scope.message = '保存に失敗しました';
    });
  }
})
<button ng-click="save()" class="btn btn-primary" ng-hide="pending">
  保存する
</button>
<button class="btn btn-primary disabled" ng-show="pending">
  保存中...
</button>
<p ng-show="message">{{message}}</p>

いきなりですがangularで開発していると、こんなコード書く機会一度はあったかと思います・・・

難しくはないですが、面倒くさいですよね?

ましてや「同じようなボタンが同じスコープにもう1個必要」となった暁にはフラグ名が重複しないようにしないといけません
ひたすらに面倒くさい・・・

そこでモジュール作りました

これを使って先ほどのコードを書き換えると面倒くささから解放されます

app.js
.controller('FooController', function ($scope, $http) {
  $scope.save = function () {
    return $http.post('http://...');
  }
})
<promise-messages for-action="save()" state="state" class="btn"
                  ng-class="{'btn-primary': state.none || state.pending}" ng-disabled="state.pending">
  <promise-message when="none">保存する</promise-message>
  <promise-message when="pending">保存中...</promise-message>
  <promise-message when="fulfilled">保存しました</promise-message>
  <promise-message when="rejected">保存に失敗しました</promise-message>
</promise-messages>

ほぼプログラムする必要がなくなり、定義だけで実現できるようになりました。
めでたしめでたし

サンプル => http://plnkr.co/edit/EVtjEEaRrgCJffxTBmtg?p=preview

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1