tokuhirom's Blog

AngularJS を本気でつかうための tips


 AngularJS 

XHR 


XHR 


angular.module('myapp.exceptionHandler', [])
.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.interceptors.push(function($q, $log, $rootScope) {
    return {
      'responseError': function(response) {
        $log.error(response);

        var h = $(response.content).find('html');
        $rootScope.$broadcast('showExceptionDialog', response);
        $q.reject(response);
      }
    };
  });
}])
.controller('ExceptionDialogCtrl', function ($scope, $http, $rootScope) {
  $rootScope.$on('showExceptionDialog', function (event, err) {
    $scope.err = err;
    $('#errorDialog').modal();
  });
});

$http  XHR bootstrap 便


X-Requested-With 


X-Requested-With 
angular.module('myapp.exceptionHandler', [])
.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHTTPRequest';
}]);

app/
  controller/
    entry.js
    comment.js
  app.js

 AngularJS  AngularJS CRUD  App !

Pagination 

<table>
  <tr ng-repeat="row in rows">
    <td>{{row.id}}</td>
    <td>{{row.name}}</td>
  </tr>
</table>
<a class="btn btn-default btn-block" ng-click="read_more()" ng-show="has_next" >Read More</a>


.controller('ctrl.foo.index', function (api, $scope) {
  $scope.rows = [];
  $scope.page = 1;

  $scope.query = function () {
    api.query({page: $scope.page}, function (dat) {
      $scope.rows = $scope.rows.concat(dat.rows);
      $scope.has_next = dat.has_next;
    });
  };
  $scope.query();

  $scope.read_more = function () {
    $scope.page++;
    $scope.query();
  };
});



Pagination 

API 


 JSON API  JSON API  ngResource ngResource  ngResource  rail 

ngResource DI

$http ( jQuery  ajax )

https://github.com/tokuhirom/angular-api-client.js 

 API client 
angular.module('myapp.api', ['AngularAPIClient'])
.factory('api', function (AngularAPIClient) {
  return {
    entry: apiClient.make([
      ['query',  'GET',  '/entry/query'],
      ['create', 'POST', '/entry/create'],
    ]),
    member: apiClient.make([
      ['query',  'GET',  '/member/query'],
    ])
  };
});

使
angular.module('myapp', ['myapp.api'])
.controller('EntryCtrl', function (api) {
  api.entry.query({}, function (dat) {
    $scope.rows = $scope.rows.concat(dat.rows);
  });
});

30

API Client 
resource 'entry', 'Entry', sub {
  get  'query';
  post 'create';
};

 MyApp::Admin::C::Entry#query  /entry/query  DSL  api-client.js !!


 tips 


AngularAPI  $  tmatsuo  $ !