<h1>Example: Promise 01</h1>
<p>ひとつの非同期処理が完了したら値を表示する(3秒かかります)。</p>
<div ng-app="myApp">
  <div ng-controller="myController">
    <button ng-click="get_data()">データを取得</button>
    <button ng-click="reset()">リセット</button>
    <p>{{ message }}</p>
    <p>{{ data }}</p>
  </div>
</div>
@import "bourbon";

body {
  padding: 1.5rem;
}
View Compiled
var service = angular.module("customServices", []);
service.factory('myService', ['$q', '$timeout', function($q, $timeout) {
  return {
    data: function(){
      //deferのインスタンスを作る(お呪いのようなもの)
      var d = $q.defer();
      
      $timeout(function(){
        d.resolve("Data:1(3秒後に取得完了)");
      }, 3000);
      
      //プロミスオブジェクトを返す
      return d.promise;
    }
  }
}]);

var app = angular.module('myApp', ['customServices']);
app.controller('myController', ['$scope', 'myService', function($scope, myService){
  
  //dataの取得完了後にthenが実行される
  $scope.get_data = function(){
    
    promise = myService.data();
    //取得中であることを明示
    $scope.message = '取得中';
    
    promise.then(function(strs){
      //成功時
      $scope.message = '取得完了';
      $scope.data = strs;
    });
    
  }
  
  $scope.reset = function(){
    $scope.data = '';
  }
}]);

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. //ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js