diff options
| author | Misko Hevery | 2012-03-26 21:18:01 -0700 | 
|---|---|---|
| committer | Misko Hevery | 2012-03-28 11:16:36 -0700 | 
| commit | 8218c4b60b82927234cf545253266f288fa936c2 (patch) | |
| tree | ce26aa1e0f273a81c7f38c85aa9849a6675f6c59 /src/ng | |
| parent | 2430f52bb97fa9d682e5f028c977c5bf94c5ec38 (diff) | |
| download | angular.js-8218c4b60b82927234cf545253266f288fa936c2.tar.bz2 | |
chore(Rakefile): get ready for modules
Diffstat (limited to 'src/ng')
| -rw-r--r-- | src/ng/http.js | 2 | ||||
| -rw-r--r-- | src/ng/httpBackend.js | 2 | ||||
| -rw-r--r-- | src/ng/resource.js | 368 | 
3 files changed, 2 insertions, 370 deletions
| diff --git a/src/ng/http.js b/src/ng/http.js index c2cbd161..e67dd496 100644 --- a/src/ng/http.js +++ b/src/ng/http.js @@ -152,7 +152,7 @@ function $HttpProvider() {       * For unit testing applications that use `$http` service, see       * {@link angular.module.ngMock.$httpBackend $httpBackend mock}.       * -     * For a higher level of abstraction, please check out the {@link angular.module.ng.$resource +     * For a higher level of abstraction, please check out the {@link angular.module.ngResource.$resource       * $resource} service.       *       * The $http API is based on the {@link angular.module.ng.$q deferred/promise APIs} exposed by diff --git a/src/ng/httpBackend.js b/src/ng/httpBackend.js index 201d1a87..abe1d8f5 100644 --- a/src/ng/httpBackend.js +++ b/src/ng/httpBackend.js @@ -18,7 +18,7 @@ var XHR = window.XMLHttpRequest || function() {   * XMLHttpRequest object or JSONP and deals with browser incompatibilities.   *   * You should never need to use this service directly, instead use the higher-level abstractions: - * {@link angular.module.ng.$http $http} or {@link angular.module.ng.$resource $resource}. + * {@link angular.module.ng.$http $http} or {@link angular.module.ngResource.$resource $resource}.   *   * During testing this implementation is swapped with {@link angular.module.ngMock.$httpBackend mock   * $httpBackend} which can be trained with responses. diff --git a/src/ng/resource.js b/src/ng/resource.js deleted file mode 100644 index 3aa48e74..00000000 --- a/src/ng/resource.js +++ /dev/null @@ -1,368 +0,0 @@ -'use strict'; - -/** - * @ngdoc object - * @name angular.module.ng.$resource - * @requires $http - * - * @description - * A factory which creates a resource object that lets you interact with - * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources. - * - * The returned resource object has action methods which provide high-level behaviors without - * the need to interact with the low level {@link angular.module.ng.$http $http} service. - * - * @param {string} url A parameterized URL template with parameters prefixed by `:` as in - *   `/user/:username`. - * - * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in - *   `actions` methods. - * - *   Each key value in the parameter object is first bound to url template if present and then any - *   excess keys are appended to the url search query after the `?`. - * - *   Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in - *   URL `/path/greet?salutation=Hello`. - * - *   If the parameter value is prefixed with `@` then the value of that parameter is extracted from - *   the data object (useful for non-GET operations). - * - * @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the - *   default set of resource actions. The declaration should be created in the following format: - * - *       {action1: {method:?, params:?, isArray:?}, - *        action2: {method:?, params:?, isArray:?}, - *        ...} - * - *   Where: - * - *   - `action` – {string} – The name of action. This name becomes the name of the method on your - *     resource object. - *   - `method` – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`, - *     and `JSONP` - *   - `params` – {object=} – Optional set of pre-bound parameters for this action. - *   - isArray – {boolean=} – If true then the returned object for this action is an array, see - *     `returns` section. - * - * @returns {Object} A resource "class" object with methods for the default set of resource actions - *   optionally extended with custom `actions`. The default set contains these actions: - * - *       { 'get':    {method:'GET'}, - *         'save':   {method:'POST'}, - *         'query':  {method:'GET', isArray:true}, - *         'remove': {method:'DELETE'}, - *         'delete': {method:'DELETE'} }; - * - *   Calling these methods invoke an {@link angular.module.ng.$http} with the specified http method, - *   destination and parameters. When the data is returned from the server then the object is an - *   instance of the resource class `save`, `remove` and `delete` actions are available on it as - *   methods with the `$` prefix. This allows you to easily perform CRUD operations (create, read, - *   update, delete) on server-side data like this: - *   <pre> -        var User = $resource('/user/:userId', {userId:'@id'}); -        var user = User.get({userId:123}, function() { -          user.abc = true; -          user.$save(); -        }); -     </pre> - * - *   It is important to realize that invoking a $resource object method immediately returns an - *   empty reference (object or array depending on `isArray`). Once the data is returned from the - *   server the existing reference is populated with the actual data. This is a useful trick since - *   usually the resource is assigned to a model which is then rendered by the view. Having an empty - *   object results in no rendering, once the data arrives from the server then the object is - *   populated with the data and the view automatically re-renders itself showing the new data. This - *   means that in most case one never has to write a callback function for the action methods. - * - *   The action methods on the class object or instance object can be invoked with the following - *   parameters: - * - *   - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])` - *   - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])` - *   - non-GET instance actions:  `instance.$action([parameters], [success], [error])` - * - * - * @example - * - * # Credit card resource - * - * <pre> -     // Define CreditCard class -     var CreditCard = $resource('/user/:userId/card/:cardId', -      {userId:123, cardId:'@id'}, { -       charge: {method:'POST', params:{charge:true}} -      }); - -     // We can retrieve a collection from the server -     var cards = CreditCard.query(); -     // GET: /user/123/card -     // server returns: [ {id:456, number:'1234', name:'Smith'} ]; - -     var card = cards[0]; -     // each item is an instance of CreditCard -     expect(card instanceof CreditCard).toEqual(true); -     card.name = "J. Smith"; -     // non GET methods are mapped onto the instances -     card.$save(); -     // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} -     // server returns: {id:456, number:'1234', name: 'J. Smith'}; - -     // our custom method is mapped as well. -     card.$charge({amount:9.99}); -     // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'} -     // server returns: {id:456, number:'1234', name: 'J. Smith'}; - -     // we can create an instance as well -     var newCard = new CreditCard({number:'0123'}); -     newCard.name = "Mike Smith"; -     newCard.$save(); -     // POST: /user/123/card {number:'0123', name:'Mike Smith'} -     // server returns: {id:789, number:'01234', name: 'Mike Smith'}; -     expect(newCard.id).toEqual(789); - * </pre> - * - * The object returned from this function execution is a resource "class" which has "static" method - * for each action in the definition. - * - * Calling these methods invoke `$http` on the `url` template with the given `method` and `params`. - * When the data is returned from the server then the object is an instance of the resource type and - * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD - * operations (create, read, update, delete) on server-side data. - -   <pre> -     var User = $resource('/user/:userId', {userId:'@id'}); -     var user = User.get({userId:123}, function() { -       user.abc = true; -       user.$save(); -     }); -   </pre> - * - *     It's worth noting that the success callback for `get`, `query` and other method gets passed - *     in the response that came from the server as well as $http header getter function, so one - *     could rewrite the above example and get access to http headers as: - * -   <pre> -     var User = $resource('/user/:userId', {userId:'@id'}); -     User.get({userId:123}, function(u, getResponseHeaders){ -       u.abc = true; -       u.$save(function(u, putResponseHeaders) { -         //u => saved user object -         //putResponseHeaders => $http header getter -       }); -     }); -   </pre> - - * # Buzz client - -   Let's look at what a buzz client created with the `$resource` service looks like: -    <doc:example> -      <doc:source jsfiddle="false"> -       <script> -         function BuzzController($resource) { -           this.userId = 'googlebuzz'; -           this.Activity = $resource( -             'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments', -             {alt:'json', callback:'JSON_CALLBACK'}, -             {get:{method:'JSONP', params:{visibility:'@self'}}, replies: {method:'JSONP', params:{visibility:'@self', comments:'@comments'}}} -           ); -         } - -         BuzzController.prototype = { -           fetch: function() { -             this.activities = this.Activity.get({userId:this.userId}); -           }, -           expandReplies: function(activity) { -             activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id}); -           } -         }; -         BuzzController.$inject = ['$resource']; -       </script> - -       <div ng-controller="BuzzController"> -         <input ng-model="userId"/> -         <button ng-click="fetch()">fetch</button> -         <hr/> -         <div ng-repeat="item in activities.data.items"> -           <h1 style="font-size: 15px;"> -             <img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> -             <a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a> -             <a href ng-click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a> -           </h1> -           {{item.object.content | html}} -           <div ng-repeat="reply in item.replies.data.items" style="margin-left: 20px;"> -             <img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> -             <a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}} -           </div> -         </div> -       </div> -      </doc:source> -      <doc:scenario> -      </doc:scenario> -    </doc:example> - */ -function $ResourceProvider() { -  this.$get = ['$http', function($http) { -    var DEFAULT_ACTIONS = { -      'get':    {method:'GET'}, -      'save':   {method:'POST'}, -      'query':  {method:'GET', isArray:true}, -      'remove': {method:'DELETE'}, -      'delete': {method:'DELETE'} -    }; - - -    function Route(template, defaults) { -      this.template = template = template + '#'; -      this.defaults = defaults || {}; -      var urlParams = this.urlParams = {}; -      forEach(template.split(/\W/), function(param){ -        if (param && template.match(new RegExp("[^\\\\]:" + param + "\\W"))) { -          urlParams[param] = true; -        } -      }); -      this.template = template.replace(/\\:/g, ':'); -    } - -    Route.prototype = { -      url: function(params) { -        var self = this, -            url = this.template, -            encodedVal; - -        params = params || {}; -        forEach(this.urlParams, function(_, urlParam){ -          encodedVal = encodeUriSegment(params[urlParam] || self.defaults[urlParam] || ""); -          url = url.replace(new RegExp(":" + urlParam + "(\\W)"), encodedVal + "$1"); -        }); -        url = url.replace(/\/?#$/, ''); -        var query = []; -        forEachSorted(params, function(value, key){ -          if (!self.urlParams[key]) { -            query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value)); -          } -        }); -        url = url.replace(/\/*$/, ''); -        return url + (query.length ? '?' + query.join('&') : ''); -      } -    }; - - -    function ResourceFactory(url, paramDefaults, actions) { -      var route = new Route(url); - -      actions = extend({}, DEFAULT_ACTIONS, actions); - -      function extractParams(data){ -        var ids = {}; -        forEach(paramDefaults || {}, function(value, key){ -          ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value; -        }); -        return ids; -      } - -      function Resource(value){ -        copy(value || {}, this); -      } - -      forEach(actions, function(action, name) { -        var isPostOrPut = action.method == 'POST' || action.method == 'PUT'; -        Resource[name] = function(a1, a2, a3, a4) { -          var params = {}; -          var data; -          var success = noop; -          var error = null; -          switch(arguments.length) { -          case 4: -            error = a4; -            success = a3; -            //fallthrough -          case 3: -          case 2: -            if (isFunction(a2)) { -              if (isFunction(a1)) { -                success = a1; -                error = a2; -                break; -              } - -              success = a2; -              error = a3; -              //fallthrough -            } else { -              params = a1; -              data = a2; -              success = a3; -              break; -            } -          case 1: -            if (isFunction(a1)) success = a1; -            else if (isPostOrPut) data = a1; -            else params = a1; -            break; -          case 0: break; -          default: -            throw "Expected between 0-4 arguments [params, data, success, error], got " + -              arguments.length + " arguments."; -          } - -          var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data)); -          $http({ -            method: action.method, -            url: route.url(extend({}, extractParams(data), action.params || {}, params)), -            data: data -          }).then(function(response) { -              var data = response.data; - -              if (data) { -                if (action.isArray) { -                  value.length = 0; -                  forEach(data, function(item) { -                    value.push(new Resource(item)); -                  }); -                } else { -                  copy(data, value); -                } -              } -              (success||noop)(value, response.headers); -            }, error); - -          return value; -        }; - - -        Resource.bind = function(additionalParamDefaults){ -          return ResourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); -        }; - - -        Resource.prototype['$' + name] = function(a1, a2, a3) { -          var params = extractParams(this), -              success = noop, -              error; - -          switch(arguments.length) { -          case 3: params = a1; success = a2; error = a3; break; -          case 2: -          case 1: -            if (isFunction(a1)) { -              success = a1; -              error = a2; -            } else { -              params = a1; -              success = a2 || noop; -            } -          case 0: break; -          default: -            throw "Expected between 1-3 arguments [params, success, error], got " + -              arguments.length + " arguments."; -          } -          var data = isPostOrPut ? this : undefined; -          Resource[name].call(this, params, data, success, error); -        }; -      }); -      return Resource; -    } - -    return ResourceFactory; -  }]; -} | 
