<h1>Example: Failure Asynchronous</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', [ '$timeout', function( $timeout) {
  return {
    data: function(){
      //deferのインスタンスを作る(お呪いのようなもの)
      var data;
      
      $timeout(function(){
        data = "Data:1(3秒後に取得完了)";
      }, 3000);
      
      //値を返す
      return data;
    }
  }
}]);

var app = angular.module('myApp', ['customServices']);
app.controller('myController', ['$scope', 'myService', function($scope, myService){
  
  $scope.get_data = function(){
    
    //値を取得する
    var data = myService.data();
    
    if(data){
      $scope.data = data;
    } else {
      $scope.data = '値が取得できません';
    }
  }
  
  $scope.reset = function(){
    $scope.data = '';
  }
}]);

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

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