From 211cbf1481059f44101059ebafc99f8d8aef8f77 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Thu, 13 Jun 2013 19:05:19 -0300 Subject: [PATCH 001/441] Added error interceptor Fixes #106 --- README.md | 3 +++ dist/restangular.js | 10 +++++++++- dist/restangular.min.js | 4 ++-- dist/restangular.zip | Bin 38727 -> 39207 bytes src/restangular.js | 8 ++++++++ 5 files changed, 22 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 2f4c692b..f63688a9 100644 --- a/README.md +++ b/README.md @@ -266,6 +266,9 @@ The requestInterceptor is called before sending any data to the server. It's a f * **what**: The model that's being requested. It can be for example: `accounts`, `buildings`, etc. * **url**: The relative URL being requested. For example: `/api/v1/accounts/123` +#### errorInterceptor +The errorInterceptor is called whenever there's an error. It's a function that receives the response as a parameter. + #### listTypeIsArray You can set in this property wether the `getList` method will return an Array or not. Most of the times, it will return an array, as it returns a collection of values. However, sometimes this method returns first some metadata and inside it has the array. So this can be used together with `responseExtractor` to get the real array. The default value is true. diff --git a/dist/restangular.js b/dist/restangular.js index c7ec661a..f12d6baf 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.2 - 2013-06-09 + * @version v0.8.2 - 2013-06-13 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT @@ -150,6 +150,12 @@ module.provider('Restangular', function() { object.setRequestInterceptor = function(interceptor) { config.requestInterceptor = interceptor; } + + config.errorInterceptor = config.errorInterceptor || function() {}; + + object.setErrorInterceptor = function(interceptor) { + config.errorInterceptor = interceptor; + } /** * This method is called after an element has been "Restangularized". @@ -527,6 +533,7 @@ module.provider('Restangular', function() { deferred.resolve(restangularizeCollection(null, processedData, __this[config.restangularFields.route])); } }, function error(response) { + config.errorInterceptor(response); deferred.reject(response); }); @@ -556,6 +563,7 @@ module.provider('Restangular', function() { }; var errorCallback = function(response) { + config.errorInterceptor(response); deferred.reject(response); }; // Overring HTTP Method diff --git a/dist/restangular.min.js b/dist/restangular.min.js index fac471a3..8a330c85 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.2 - 2013-06-09 + * @version v0.8.2 - 2013-06-13 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",["ngResource"]);a.provider("Restangular",function(){var a={};a.init=function(a,b){var c=["get","head","options","trace"];b.isSafe=function(a){return _.contains(c,a)},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=b.withHttpDefaults||function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",what:"restangularWhat"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},b.listTypeIsArray=_.isUndefined(b.listTypeIsArray)?!0:b.listTypeIsArray,a.setListTypeIsArray=function(a){b.listTypeIsArray=a},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var d=function(){};d.prototype.parentsArray=function(a){for(var c=[];!_.isUndefined(a);)c.push(a),a=a[b.restangularFields.parentResource];return c.reverse()},d.prototype.resource=function(a,c,d,e){var f=this.base(a);return f+=e[b.restangularFields.what]?"/:"+b.restangularFields.what:"",f+=b.suffix||"",c(f,{},{getList:b.withHttpDefaults({method:"GET",params:b.defaultRequestParams,isArray:b.listTypeIsArray,headers:d||{}}),get:b.withHttpDefaults({method:"GET",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),put:b.withHttpDefaults({method:"PUT",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),post:b.withHttpDefaults({method:"POST",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),remove:b.withHttpDefaults({method:"DELETE",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),head:b.withHttpDefaults({method:"HEAD",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),trace:b.withHttpDefaults({method:"TRACE",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),options:b.withHttpDefaults({method:"OPTIONS",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),patch:b.withHttpDefaults({method:"PATCH",params:b.defaultRequestParams,isArray:!1,headers:d||{}})})};var e=function(){};e.prototype=new d,e.prototype.base=function(a){return b.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.restangularFields.route];return c[b.restangularFields.restangularCollection]||(d+="/"+b.getIdFromElem(c)),d},"")},e.prototype.fetchUrl=function(a,c){var d=this.base(a);return c&&c[b.restangularFields.what]&&(d+="/"+c[b.restangularFields.what]),d},b.urlCreatorFactory.path=e};var b={};a.init(this,b),this.$get=["$resource","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(D,a,b)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,G)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),n(d),f.transformElem(d,!0,c,G)}function r(a){var b={};return a&&(b[f.restangularFields.what]=a),b}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=r(a),h=this,i=d.defer(),k="getList",l=H.fetchUrl(this,g),m=a||h[f.restangularFields.route],n=_.extend(g,b);return f.requestInterceptor(null,k,m,l),H.resource(this,c,e,n).getList(n,function(b){var c=f.responseExtractor(b,k,m,l),d=_.map(c,function(b){return h[f.restangularFields.restangularCollection]?p(h[f.restangularFields.parentResource],b,h[f.restangularFields.route]):p(h,b,a)});d=_.extend(c,d),h[f.restangularFields.restangularCollection]?i.resolve(q(null,d,h[f.restangularFields.route])):i.resolve(q(h,d,a))},function(a){i.reject(a)}),j(i.promise,!0)}function u(a,b,e,g){var h=this,i=d.defer(),k=b||{},l=e||this,n=k[f.restangularFields.what]||this[f.restangularFields.route],o=H.fetchUrl(this,k),q=e||m(this);q=f.requestInterceptor(q,a,n,o);var r=function(b){var c=f.responseExtractor(b,a,n,o)||l;"post"!==a||h[f.restangularFields.restangularCollection]?i.resolve(p(h[f.restangularFields.parentResource],c,h[f.restangularFields.route])):i.resolve(p(h,c,k[f.restangularFields.what]))},s=function(a){i.reject(a)},t=a,u=_.extend({},g),v=f.isOverridenMethod(a);return v&&(t="post",u=_.extend(u,{"X-HTTP-Method-Override":a})),f.isSafe(a)?v?H.resource(this,c,u,k)[t](k,{},r,s):H.resource(this,c,u,k)[t](k,r,s):H.resource(this,c,u,k)[t](k,q,r,s),j(i.promise)}function v(a,b){return _.bind(u,this)("get",a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",a,void 0,b)}function x(a,b){return _.bind(u,this)("put",a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",_.extend(r(a),c),b,d)}function z(a,b){return _.bind(u,this)("head",a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",a,void 0,b)}function B(a,b){return _.bind(u,this)("options",a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,_.extend(r(b),c),e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return G.copy=_.bind(o,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(p,G),G.restangularizeCollection=_.bind(q,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",["ngResource"]);a.provider("Restangular",function(){var a={};a.init=function(a,b){var c=["get","head","options","trace"];b.isSafe=function(a){return _.contains(c,a)},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=b.withHttpDefaults||function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",what:"restangularWhat"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},b.listTypeIsArray=_.isUndefined(b.listTypeIsArray)?!0:b.listTypeIsArray,a.setListTypeIsArray=function(a){b.listTypeIsArray=a},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var d=function(){};d.prototype.parentsArray=function(a){for(var c=[];!_.isUndefined(a);)c.push(a),a=a[b.restangularFields.parentResource];return c.reverse()},d.prototype.resource=function(a,c,d,e){var f=this.base(a);return f+=e[b.restangularFields.what]?"/:"+b.restangularFields.what:"",f+=b.suffix||"",c(f,{},{getList:b.withHttpDefaults({method:"GET",params:b.defaultRequestParams,isArray:b.listTypeIsArray,headers:d||{}}),get:b.withHttpDefaults({method:"GET",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),put:b.withHttpDefaults({method:"PUT",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),post:b.withHttpDefaults({method:"POST",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),remove:b.withHttpDefaults({method:"DELETE",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),head:b.withHttpDefaults({method:"HEAD",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),trace:b.withHttpDefaults({method:"TRACE",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),options:b.withHttpDefaults({method:"OPTIONS",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),patch:b.withHttpDefaults({method:"PATCH",params:b.defaultRequestParams,isArray:!1,headers:d||{}})})};var e=function(){};e.prototype=new d,e.prototype.base=function(a){return b.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.restangularFields.route];return c[b.restangularFields.restangularCollection]||(d+="/"+b.getIdFromElem(c)),d},"")},e.prototype.fetchUrl=function(a,c){var d=this.base(a);return c&&c[b.restangularFields.what]&&(d+="/"+c[b.restangularFields.what]),d},b.urlCreatorFactory.path=e};var b={};a.init(this,b),this.$get=["$resource","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(D,a,b)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,G)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),n(d),f.transformElem(d,!0,c,G)}function r(a){var b={};return a&&(b[f.restangularFields.what]=a),b}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=r(a),h=this,i=d.defer(),k="getList",l=H.fetchUrl(this,g),m=a||h[f.restangularFields.route],n=_.extend(g,b);return f.requestInterceptor(null,k,m,l),H.resource(this,c,e,n).getList(n,function(b){var c=f.responseExtractor(b,k,m,l),d=_.map(c,function(b){return h[f.restangularFields.restangularCollection]?p(h[f.restangularFields.parentResource],b,h[f.restangularFields.route]):p(h,b,a)});d=_.extend(c,d),h[f.restangularFields.restangularCollection]?i.resolve(q(null,d,h[f.restangularFields.route])):i.resolve(q(h,d,a))},function(a){f.errorInterceptor(a),i.reject(a)}),j(i.promise,!0)}function u(a,b,e,g){var h=this,i=d.defer(),k=b||{},l=e||this,n=k[f.restangularFields.what]||this[f.restangularFields.route],o=H.fetchUrl(this,k),q=e||m(this);q=f.requestInterceptor(q,a,n,o);var r=function(b){var c=f.responseExtractor(b,a,n,o)||l;"post"!==a||h[f.restangularFields.restangularCollection]?i.resolve(p(h[f.restangularFields.parentResource],c,h[f.restangularFields.route])):i.resolve(p(h,c,k[f.restangularFields.what]))},s=function(a){f.errorInterceptor(a),i.reject(a)},t=a,u=_.extend({},g),v=f.isOverridenMethod(a);return v&&(t="post",u=_.extend(u,{"X-HTTP-Method-Override":a})),f.isSafe(a)?v?H.resource(this,c,u,k)[t](k,{},r,s):H.resource(this,c,u,k)[t](k,r,s):H.resource(this,c,u,k)[t](k,q,r,s),j(i.promise)}function v(a,b){return _.bind(u,this)("get",a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",a,void 0,b)}function x(a,b){return _.bind(u,this)("put",a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",_.extend(r(a),c),b,d)}function z(a,b){return _.bind(u,this)("head",a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",a,void 0,b)}function B(a,b){return _.bind(u,this)("options",a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,_.extend(r(b),c),e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return G.copy=_.bind(o,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(p,G),G.restangularizeCollection=_.bind(q,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index fc00d88594a4761d13f54ee48ef71128652fd2a3..b1983d7288c4de6ce5a4f4d2e319b269d22f7b58 100644 GIT binary patch delta 452 zcmX@Uj%oQOCf)#VW)?065Lhzf>_lD#J|N{ZMd9?b{9*=%{Njn$*-VDU8&_~jOn#@% zJ9(ZsyKQPwQGStUUP)?Ea%w?IevyK$LUMjyT4uT)hD=S3LRx8Fa!F=>o`$AEb*(km z#!s5>yx%5>zHnF3JabV&aMwo7WU?XSYGO!8QrQSSXrVp%=rm&mPy`?x X&%huKjvW|rxOlR}bWOI186W`wXuqTd delta 213 zcmZ3!iRt({Cf)#VW)?065ZE~5Y~Z_ WizUSZyjj^mLd-z86G&G~1MvXo;6<7M diff --git a/src/restangular.js b/src/restangular.js index a1821629..30ac941f 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -143,6 +143,12 @@ module.provider('Restangular', function() { object.setRequestInterceptor = function(interceptor) { config.requestInterceptor = interceptor; } + + config.errorInterceptor = config.errorInterceptor || function() {}; + + object.setErrorInterceptor = function(interceptor) { + config.errorInterceptor = interceptor; + } /** * This method is called after an element has been "Restangularized". @@ -520,6 +526,7 @@ module.provider('Restangular', function() { deferred.resolve(restangularizeCollection(null, processedData, __this[config.restangularFields.route])); } }, function error(response) { + config.errorInterceptor(response); deferred.reject(response); }); @@ -549,6 +556,7 @@ module.provider('Restangular', function() { }; var errorCallback = function(response) { + config.errorInterceptor(response); deferred.reject(response); }; // Overring HTTP Method From a3b2f7b061b9be1f8daf67eee9afe0df63c9c1f1 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Thu, 13 Jun 2013 19:13:13 -0300 Subject: [PATCH 002/441] Config now used in URLHandler as well Fixes #107 --- dist/restangular.js | 66 ++++++++++++++++++++++------------------ dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 39207 -> 39904 bytes src/restangular.js | 66 ++++++++++++++++++++++------------------ 4 files changed, 73 insertions(+), 61 deletions(-) diff --git a/dist/restangular.js b/dist/restangular.js index f12d6baf..4fea060e 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -246,63 +246,67 @@ module.provider('Restangular', function() { var BaseCreator = function() { }; + BaseCreator.prototype.setConfig = function(config) { + this.config = config; + } + BaseCreator.prototype.parentsArray = function(current) { var parents = []; while(!_.isUndefined(current)) { parents.push(current); - current = current[config.restangularFields.parentResource]; + current = current[this.config.restangularFields.parentResource]; } return parents.reverse(); } BaseCreator.prototype.resource = function(current, $resource, headers, params) { var url = this.base(current); - url += params[config.restangularFields.what] ? - ("/:" + config.restangularFields.what) : ''; - url += (config.suffix || ''); + url += params[this.config.restangularFields.what] ? + ("/:" + this.config.restangularFields.what) : ''; + url += (this.config.suffix || ''); return $resource(url, {}, { - getList: config.withHttpDefaults({method: 'GET', - params: config.defaultRequestParams, - isArray: config.listTypeIsArray, + getList: this.config.withHttpDefaults({method: 'GET', + params: this.config.defaultRequestParams, + isArray: this.config.listTypeIsArray, headers: headers || {}}), - get: config.withHttpDefaults({method: 'GET', - params: config.defaultRequestParams, + get: this.config.withHttpDefaults({method: 'GET', + params: this.config.defaultRequestParams, isArray: false, headers: headers || {}}), - put: config.withHttpDefaults({method: 'PUT', - params: config.defaultRequestParams, + put: this.config.withHttpDefaults({method: 'PUT', + params: this.config.defaultRequestParams, isArray: false, headers: headers || {}}), - post: config.withHttpDefaults({method: 'POST', - params: config.defaultRequestParams, + post: this.config.withHttpDefaults({method: 'POST', + params: this.config.defaultRequestParams, isArray: false, headers: headers || {}}), - remove: config.withHttpDefaults({method: 'DELETE', - params: config.defaultRequestParams, + remove: this.config.withHttpDefaults({method: 'DELETE', + params: this.config.defaultRequestParams, isArray: false, headers: headers || {}}), - head: config.withHttpDefaults({method: 'HEAD', - params: config.defaultRequestParams, + head: this.config.withHttpDefaults({method: 'HEAD', + params: this.config.defaultRequestParams, isArray: false, headers: headers || {}}), - trace: config.withHttpDefaults({method: 'TRACE', - params: config.defaultRequestParams, + trace: this.config.withHttpDefaults({method: 'TRACE', + params: this.config.defaultRequestParams, isArray: false, headers: headers || {}}), - options: config.withHttpDefaults({method: 'OPTIONS', - params: config.defaultRequestParams, + options: this.config.withHttpDefaults({method: 'OPTIONS', + params: this.config.defaultRequestParams, isArray: false, headers: headers || {}}), - patch: config.withHttpDefaults({method: 'PATCH', - params: config.defaultRequestParams, + patch: this.config.withHttpDefaults({method: 'PATCH', + params: this.config.defaultRequestParams, isArray: false, headers: headers || {}}) }); @@ -319,11 +323,12 @@ module.provider('Restangular', function() { Path.prototype = new BaseCreator(); Path.prototype.base = function(current) { - return config.baseUrl + _.reduce(this.parentsArray(current), function(acum, elem) { - var currUrl = acum + "/" + elem[config.restangularFields.route]; + var __this = this; + return this.config.baseUrl + _.reduce(this.parentsArray(current), function(acum, elem) { + var currUrl = acum + "/" + elem[__this.config.restangularFields.route]; - if (!elem[config.restangularFields.restangularCollection]) { - currUrl += "/" + config.getIdFromElem(elem); + if (!elem[__this.config.restangularFields.restangularCollection]) { + currUrl += "/" + __this.config.getIdFromElem(elem); } return currUrl; @@ -334,8 +339,8 @@ module.provider('Restangular', function() { Path.prototype.fetchUrl = function(current, params) { var baseUrl = this.base(current); - if (params && params[config.restangularFields.what]) { - baseUrl += "/" + params[config.restangularFields.what]; + if (params && params[this.config.restangularFields.what]) { + baseUrl += "/" + params[this.config.restangularFields.what]; } return baseUrl; } @@ -359,7 +364,8 @@ module.provider('Restangular', function() { var service = {}; var urlHandler = new config.urlCreatorFactory[config.urlCreator](); - + urlHandler.setConfig(config); + function restangularizeBase(parent, elem, route) { elem[config.restangularFields.route] = route; elem.getRestangularUrl = _.bind(urlHandler.fetchUrl, urlHandler, elem); diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 8a330c85..b16c6576 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -5,4 +5,4 @@ * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",["ngResource"]);a.provider("Restangular",function(){var a={};a.init=function(a,b){var c=["get","head","options","trace"];b.isSafe=function(a){return _.contains(c,a)},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=b.withHttpDefaults||function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",what:"restangularWhat"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},b.listTypeIsArray=_.isUndefined(b.listTypeIsArray)?!0:b.listTypeIsArray,a.setListTypeIsArray=function(a){b.listTypeIsArray=a},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var d=function(){};d.prototype.parentsArray=function(a){for(var c=[];!_.isUndefined(a);)c.push(a),a=a[b.restangularFields.parentResource];return c.reverse()},d.prototype.resource=function(a,c,d,e){var f=this.base(a);return f+=e[b.restangularFields.what]?"/:"+b.restangularFields.what:"",f+=b.suffix||"",c(f,{},{getList:b.withHttpDefaults({method:"GET",params:b.defaultRequestParams,isArray:b.listTypeIsArray,headers:d||{}}),get:b.withHttpDefaults({method:"GET",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),put:b.withHttpDefaults({method:"PUT",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),post:b.withHttpDefaults({method:"POST",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),remove:b.withHttpDefaults({method:"DELETE",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),head:b.withHttpDefaults({method:"HEAD",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),trace:b.withHttpDefaults({method:"TRACE",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),options:b.withHttpDefaults({method:"OPTIONS",params:b.defaultRequestParams,isArray:!1,headers:d||{}}),patch:b.withHttpDefaults({method:"PATCH",params:b.defaultRequestParams,isArray:!1,headers:d||{}})})};var e=function(){};e.prototype=new d,e.prototype.base=function(a){return b.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.restangularFields.route];return c[b.restangularFields.restangularCollection]||(d+="/"+b.getIdFromElem(c)),d},"")},e.prototype.fetchUrl=function(a,c){var d=this.base(a);return c&&c[b.restangularFields.what]&&(d+="/"+c[b.restangularFields.what]),d},b.urlCreatorFactory.path=e};var b={};a.init(this,b),this.$get=["$resource","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(D,a,b)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,G)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),n(d),f.transformElem(d,!0,c,G)}function r(a){var b={};return a&&(b[f.restangularFields.what]=a),b}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=r(a),h=this,i=d.defer(),k="getList",l=H.fetchUrl(this,g),m=a||h[f.restangularFields.route],n=_.extend(g,b);return f.requestInterceptor(null,k,m,l),H.resource(this,c,e,n).getList(n,function(b){var c=f.responseExtractor(b,k,m,l),d=_.map(c,function(b){return h[f.restangularFields.restangularCollection]?p(h[f.restangularFields.parentResource],b,h[f.restangularFields.route]):p(h,b,a)});d=_.extend(c,d),h[f.restangularFields.restangularCollection]?i.resolve(q(null,d,h[f.restangularFields.route])):i.resolve(q(h,d,a))},function(a){f.errorInterceptor(a),i.reject(a)}),j(i.promise,!0)}function u(a,b,e,g){var h=this,i=d.defer(),k=b||{},l=e||this,n=k[f.restangularFields.what]||this[f.restangularFields.route],o=H.fetchUrl(this,k),q=e||m(this);q=f.requestInterceptor(q,a,n,o);var r=function(b){var c=f.responseExtractor(b,a,n,o)||l;"post"!==a||h[f.restangularFields.restangularCollection]?i.resolve(p(h[f.restangularFields.parentResource],c,h[f.restangularFields.route])):i.resolve(p(h,c,k[f.restangularFields.what]))},s=function(a){f.errorInterceptor(a),i.reject(a)},t=a,u=_.extend({},g),v=f.isOverridenMethod(a);return v&&(t="post",u=_.extend(u,{"X-HTTP-Method-Override":a})),f.isSafe(a)?v?H.resource(this,c,u,k)[t](k,{},r,s):H.resource(this,c,u,k)[t](k,r,s):H.resource(this,c,u,k)[t](k,q,r,s),j(i.promise)}function v(a,b){return _.bind(u,this)("get",a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",a,void 0,b)}function x(a,b){return _.bind(u,this)("put",a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",_.extend(r(a),c),b,d)}function z(a,b){return _.bind(u,this)("head",a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",a,void 0,b)}function B(a,b){return _.bind(u,this)("options",a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,_.extend(r(b),c),e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return G.copy=_.bind(o,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(p,G),G.restangularizeCollection=_.bind(q,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",["ngResource"]);a.provider("Restangular",function(){var a={};a.init=function(a,b){var c=["get","head","options","trace"];b.isSafe=function(a){return _.contains(c,a)},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=b.withHttpDefaults||function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",what:"restangularWhat"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},b.listTypeIsArray=_.isUndefined(b.listTypeIsArray)?!0:b.listTypeIsArray,a.setListTypeIsArray=function(a){b.listTypeIsArray=a},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var d=function(){};d.prototype.setConfig=function(a){this.config=a},d.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},d.prototype.resource=function(a,b,c,d){var e=this.base(a);return e+=d[this.config.restangularFields.what]?"/:"+this.config.restangularFields.what:"",e+=this.config.suffix||"",b(e,{},{getList:this.config.withHttpDefaults({method:"GET",params:this.config.defaultRequestParams,isArray:this.config.listTypeIsArray,headers:c||{}}),get:this.config.withHttpDefaults({method:"GET",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}}),put:this.config.withHttpDefaults({method:"PUT",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}}),post:this.config.withHttpDefaults({method:"POST",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}})})};var e=function(){};e.prototype=new d,e.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];return c[b.config.restangularFields.restangularCollection]||(d+="/"+b.config.getIdFromElem(c)),d},"")},e.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&b[this.config.restangularFields.what]&&(c+="/"+b[this.config.restangularFields.what]),c},b.urlCreatorFactory.path=e};var b={};a.init(this,b),this.$get=["$resource","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(D,a,b)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,G)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),n(d),f.transformElem(d,!0,c,G)}function r(a){var b={};return a&&(b[f.restangularFields.what]=a),b}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=r(a),h=this,i=d.defer(),k="getList",l=H.fetchUrl(this,g),m=a||h[f.restangularFields.route],n=_.extend(g,b);return f.requestInterceptor(null,k,m,l),H.resource(this,c,e,n).getList(n,function(b){var c=f.responseExtractor(b,k,m,l),d=_.map(c,function(b){return h[f.restangularFields.restangularCollection]?p(h[f.restangularFields.parentResource],b,h[f.restangularFields.route]):p(h,b,a)});d=_.extend(c,d),h[f.restangularFields.restangularCollection]?i.resolve(q(null,d,h[f.restangularFields.route])):i.resolve(q(h,d,a))},function(a){f.errorInterceptor(a),i.reject(a)}),j(i.promise,!0)}function u(a,b,e,g){var h=this,i=d.defer(),k=b||{},l=e||this,n=k[f.restangularFields.what]||this[f.restangularFields.route],o=H.fetchUrl(this,k),q=e||m(this);q=f.requestInterceptor(q,a,n,o);var r=function(b){var c=f.responseExtractor(b,a,n,o)||l;"post"!==a||h[f.restangularFields.restangularCollection]?i.resolve(p(h[f.restangularFields.parentResource],c,h[f.restangularFields.route])):i.resolve(p(h,c,k[f.restangularFields.what]))},s=function(a){f.errorInterceptor(a),i.reject(a)},t=a,u=_.extend({},g),v=f.isOverridenMethod(a);return v&&(t="post",u=_.extend(u,{"X-HTTP-Method-Override":a})),f.isSafe(a)?v?H.resource(this,c,u,k)[t](k,{},r,s):H.resource(this,c,u,k)[t](k,r,s):H.resource(this,c,u,k)[t](k,q,r,s),j(i.promise)}function v(a,b){return _.bind(u,this)("get",a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",a,void 0,b)}function x(a,b){return _.bind(u,this)("put",a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",_.extend(r(a),c),b,d)}function z(a,b){return _.bind(u,this)("head",a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",a,void 0,b)}function B(a,b){return _.bind(u,this)("options",a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,_.extend(r(b),c),e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),G.copy=_.bind(o,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(p,G),G.restangularizeCollection=_.bind(q,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index b1983d7288c4de6ce5a4f4d2e319b269d22f7b58..1cf1dc8a2a97ca7decb49eece45424897f878f86 100644 GIT binary patch delta 1554 zcmaJ>PfXKb6dz+7bBsR&#+(r>Lq^NW20@KdD=JY@(Ci?I2`aQ*$Ck*ptQ|3Kn1P@P ziHYW!C@~r@Vq(;wI~Xs<0}(GqO}r6>lg5LISG{Qek9LMNSzo{Re((3b@BQBQ=!JRx zrP&!CEVnpJ;%{-`rn9AbapC>p_s4&KSmsTpW&SyFs=bzD`Tk@g8XreUB$`PuFtE1? ze)idG8Ff`Q2zZ@r2Cn^!m5;@_U?Ge)m&qpFaCzauSsPr(nsh4`SiulwAG<||W4t|a0Qj%sA{@TAjj zp!nR`QS?{FSSn)Vcoy84VJuW($Z#!$X&J!aW4Z#GZ{C@rcqV2{-`8D)bA{Dziy4rE z!U2x#fE%rLi+JSlt!KJobX4B@uQS^K8M8vwa07fi;fA%HwyGBP0y{BMj2HylZkLKE zcy=GrH_Qr`_H-$A$t|=N-tBRk;qh=yohA!ZZa+rAr~O{IPFBO$V_wJ)x#1wu4EbHQ z!qC3yUP)O8R&1Y^+XQ8`6;`>UPQR9e6otjdlL?f+|74;D(ZdTqYWgU(DqM4~?>Tb_&mqv;0t8(3DIq zi>^^?=yu3Yt8x3 zTGs=v%~X{F8dN}FTNvA3EJX;KNf?nwn6vErp~GiN{vPz|+~GCQ&4`)O148kd#H% zB$Uk^0d>00&p8D4j7v5Zlt=`+wsT8lYuXOQZ3i|4 zPX6Teu*k(k5{?FU@MK~%(SyN|n3#AYF>+M7aJKDQCXpund*0`HzOUc=^xJ)--+Zk% zMXpp;*CFz;QG9B$H*FNR&p$&y@1+C;kxv@}TkE#1Yr}5PW1k@JZwKF_1~|YD;KGe| zsPlBgK7Ja)9u!2+EbJFh_(iy3tI!D}gdM_#R>%>dBltUC@&uO_{iuR|A(L4@!d2^4_?}PWrxn{tr(l@wIwNFSk9j2tD> zaTRy|yc`~s@1=ubs~(7}ZSZ~EQVRRO`YrMb8-9>2b4~=AbC!D3mrSs^ zWOviS>DvMOtT!P{CK)!CNU{t@;Q^fXa%mwhJ(5(AnvMcR+2j_~26$FX^GTEjXP$J^ zBtx=zW`W|-SWt{71aFiQSlK|O#fTs)sh9F+bn>;e$M0~E5*YOg=~ygrKbw`_X)H!& za%AQXD~1wMFQTx!dJ&1P~r zoRrkZC~an~E;nCsHb*8W93)5a)Vv@eR_L!KN5g=mR{uOGu~)R<~QWUl9Msud%7 zf~wK@*yzRohiuS{M4qDAG8Oh7S}I;vjiH69yfiZ_jTO$JOF33$#KH_+wtB5Yw9?#WIaBr7EXEK)htEMoVPGu)Zx?Gjj_WGza>=r#e4E+j(j+QU yg_BI_=NfH=o6kS$H;T};-lwFm@_)n3`T%+~kO Date: Thu, 13 Jun 2013 19:15:12 -0300 Subject: [PATCH 003/441] v0.8.3 --- CHANGELOG.md | 7 ++++++- bower.json | 2 +- dist/restangular.js | 2 +- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 39904 -> 39884 bytes package.json | 2 +- 6 files changed, 10 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 86976dc3..753380a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,12 @@ +#0.8.3 +* Fixed bug with URLHandler. Now it uses local configuration as well +* Added error interceptor +* Fixed minor bugs + + #0.8.0 * Big refactor to use scoped configurations - #0.7.3 * All configuration can be done via either `Restangular` or `RestangularProvider` * url field now is called getRestangularUrl diff --git a/bower.json b/bower.json index e5e8d70a..08cc58c6 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "0.8.2", + "version": "0.8.3", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { diff --git a/dist/restangular.js b/dist/restangular.js index 4fea060e..45f911cf 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.2 - 2013-06-13 + * @version v0.8.3 - 2013-06-13 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.min.js b/dist/restangular.min.js index b16c6576..f722ad3b 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.2 - 2013-06-13 + * @version v0.8.3 - 2013-06-13 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.zip b/dist/restangular.zip index 1cf1dc8a2a97ca7decb49eece45424897f878f86..6f7d77997fef34c52bb9df0e4e235db5b614a65a 100644 GIT binary patch delta 384 zcmaE`o$1VWChh=lW)?065O^|?TS@52%(G5G+8vWOlrS)WurR~qjkAR(26-?VZ=7AG zIoVNLc(SV2Eg&sES)hPpvb?t9WVHeyTaR;cqP7fJ+@XMTvV)%5}P7Te!hAU*(v COn27+ delta 334 zcmX@Jo$0}LChh=lW)?065Lh;mTZwns%(G5sJ%64*Qo_J+WTI69qtWDs(yf~V7!PVp zUT7#XSw-s>kd~O7W1tD9*BEe4j?i&^APq3!6Mo2UDy@*BC=xjGj4$n1ep1 zIt2q$G*%T_IP;k diff --git a/package.json b/package.json index e66bfdb0..1c3f49c8 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "restangular", "description": "Restfull Resources service for AngularJS apps", - "version": "0.8.2", + "version": "0.8.3", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", "author": "Martin Gontovnikas ", From 4d19c8ae267661b942439f36fd866327dbe04f85 Mon Sep 17 00:00:00 2001 From: PowerKiKi Date: Mon, 17 Jun 2013 12:11:17 +0900 Subject: [PATCH 004/441] Fix minor typo --- test/restangularSpec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/restangularSpec.js b/test/restangularSpec.js index a00b0afe..2b9268e8 100644 --- a/test/restangularSpec.js +++ b/test/restangularSpec.js @@ -203,7 +203,7 @@ describe("Restangular", function() { }); - it("Custom GET methods sohuld work", function() { + it("Custom GET methods should work", function() { restangularAccount1.customGET("message").then(function(msg) { expect(sanitizeRestangularOne(msg)).toEqual(messages[0]); }); From c77d9e62e2c9dfea58b0dfd0ef91881fdb3bb67c Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Thu, 20 Jun 2013 00:45:01 -0300 Subject: [PATCH 005/441] Added default headers Fixes #105 --- README.md | 4 ++++ dist/restangular.js | 15 ++++++++++++--- dist/restangular.min.js | 4 ++-- dist/restangular.zip | Bin 39884 -> 40282 bytes src/restangular.js | 13 +++++++++++-- 5 files changed, 29 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index f63688a9..ac27b843 100644 --- a/README.md +++ b/README.md @@ -293,6 +293,10 @@ You can now Override HTTP Methods. You can set here the array of methods to over You can set default Query parameters to be sent with every request +#### defaultHeaders + +You can set default Headers to be sent with every request. + #### requestSuffix If all of your requests require to send some suffix to work, you can set it here. For example, if you need to send the format like `/users/123.json`you can add that `.json` to the suffix using the `setRequestSuffix`method diff --git a/dist/restangular.js b/dist/restangular.js index 45f911cf..b2da0c1f 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.3 - 2013-06-13 + * @version v0.8.3 - 2013-06-20 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT @@ -44,7 +44,7 @@ module.provider('Restangular', function() { config.defaultHttpFields = values; } - config.withHttpDefaults = config.withHttpDefaults || function(obj) { + config.withHttpDefaults = function(obj) { return _.defaults(obj, config.defaultHttpFields); } @@ -53,6 +53,11 @@ module.provider('Restangular', function() { config.defaultRequestParams = values; } + config.defaultHeaders = config.defaultHeaders || {}; + object.setDefaultHeaders = function(headers) { + config.defaultHeaders = headers; + } + /** * Method overriders will set which methods are sent via POST with an X-HTTP-Method-Override **/ @@ -259,11 +264,15 @@ module.provider('Restangular', function() { return parents.reverse(); } - BaseCreator.prototype.resource = function(current, $resource, headers, params) { + BaseCreator.prototype.resource = function(current, $resource, callHeaders, params) { + var url = this.base(current); url += params[this.config.restangularFields.what] ? ("/:" + this.config.restangularFields.what) : ''; url += (this.config.suffix || ''); + + var headers = _.defaults(callHeaders, this.config.defaultHeaders); + return $resource(url, {}, { getList: this.config.withHttpDefaults({method: 'GET', params: this.config.defaultRequestParams, diff --git a/dist/restangular.min.js b/dist/restangular.min.js index f722ad3b..4c4e9a2f 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.3 - 2013-06-13 + * @version v0.8.3 - 2013-06-20 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",["ngResource"]);a.provider("Restangular",function(){var a={};a.init=function(a,b){var c=["get","head","options","trace"];b.isSafe=function(a){return _.contains(c,a)},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=b.withHttpDefaults||function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",what:"restangularWhat"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},b.listTypeIsArray=_.isUndefined(b.listTypeIsArray)?!0:b.listTypeIsArray,a.setListTypeIsArray=function(a){b.listTypeIsArray=a},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var d=function(){};d.prototype.setConfig=function(a){this.config=a},d.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},d.prototype.resource=function(a,b,c,d){var e=this.base(a);return e+=d[this.config.restangularFields.what]?"/:"+this.config.restangularFields.what:"",e+=this.config.suffix||"",b(e,{},{getList:this.config.withHttpDefaults({method:"GET",params:this.config.defaultRequestParams,isArray:this.config.listTypeIsArray,headers:c||{}}),get:this.config.withHttpDefaults({method:"GET",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}}),put:this.config.withHttpDefaults({method:"PUT",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}}),post:this.config.withHttpDefaults({method:"POST",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:this.config.defaultRequestParams,isArray:!1,headers:c||{}})})};var e=function(){};e.prototype=new d,e.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];return c[b.config.restangularFields.restangularCollection]||(d+="/"+b.config.getIdFromElem(c)),d},"")},e.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&b[this.config.restangularFields.what]&&(c+="/"+b[this.config.restangularFields.what]),c},b.urlCreatorFactory.path=e};var b={};a.init(this,b),this.$get=["$resource","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(D,a,b)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,G)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),n(d),f.transformElem(d,!0,c,G)}function r(a){var b={};return a&&(b[f.restangularFields.what]=a),b}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=r(a),h=this,i=d.defer(),k="getList",l=H.fetchUrl(this,g),m=a||h[f.restangularFields.route],n=_.extend(g,b);return f.requestInterceptor(null,k,m,l),H.resource(this,c,e,n).getList(n,function(b){var c=f.responseExtractor(b,k,m,l),d=_.map(c,function(b){return h[f.restangularFields.restangularCollection]?p(h[f.restangularFields.parentResource],b,h[f.restangularFields.route]):p(h,b,a)});d=_.extend(c,d),h[f.restangularFields.restangularCollection]?i.resolve(q(null,d,h[f.restangularFields.route])):i.resolve(q(h,d,a))},function(a){f.errorInterceptor(a),i.reject(a)}),j(i.promise,!0)}function u(a,b,e,g){var h=this,i=d.defer(),k=b||{},l=e||this,n=k[f.restangularFields.what]||this[f.restangularFields.route],o=H.fetchUrl(this,k),q=e||m(this);q=f.requestInterceptor(q,a,n,o);var r=function(b){var c=f.responseExtractor(b,a,n,o)||l;"post"!==a||h[f.restangularFields.restangularCollection]?i.resolve(p(h[f.restangularFields.parentResource],c,h[f.restangularFields.route])):i.resolve(p(h,c,k[f.restangularFields.what]))},s=function(a){f.errorInterceptor(a),i.reject(a)},t=a,u=_.extend({},g),v=f.isOverridenMethod(a);return v&&(t="post",u=_.extend(u,{"X-HTTP-Method-Override":a})),f.isSafe(a)?v?H.resource(this,c,u,k)[t](k,{},r,s):H.resource(this,c,u,k)[t](k,r,s):H.resource(this,c,u,k)[t](k,q,r,s),j(i.promise)}function v(a,b){return _.bind(u,this)("get",a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",a,void 0,b)}function x(a,b){return _.bind(u,this)("put",a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",_.extend(r(a),c),b,d)}function z(a,b){return _.bind(u,this)("head",a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",a,void 0,b)}function B(a,b){return _.bind(u,this)("options",a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,_.extend(r(b),c),e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),G.copy=_.bind(o,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(p,G),G.restangularizeCollection=_.bind(q,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",["ngResource"]);a.provider("Restangular",function(){var a={};a.init=function(a,b){var c=["get","head","options","trace"];b.isSafe=function(a){return _.contains(c,a)},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",what:"restangularWhat"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},b.listTypeIsArray=_.isUndefined(b.listTypeIsArray)?!0:b.listTypeIsArray,a.setListTypeIsArray=function(a){b.listTypeIsArray=a},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var d=function(){};d.prototype.setConfig=function(a){this.config=a},d.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},d.prototype.resource=function(a,b,c,d){var e=this.base(a);e+=d[this.config.restangularFields.what]?"/:"+this.config.restangularFields.what:"",e+=this.config.suffix||"";var f=_.defaults(c,this.config.defaultHeaders);return b(e,{},{getList:this.config.withHttpDefaults({method:"GET",params:this.config.defaultRequestParams,isArray:this.config.listTypeIsArray,headers:f||{}}),get:this.config.withHttpDefaults({method:"GET",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}}),put:this.config.withHttpDefaults({method:"PUT",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}}),post:this.config.withHttpDefaults({method:"POST",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}})})};var e=function(){};e.prototype=new d,e.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];return c[b.config.restangularFields.restangularCollection]||(d+="/"+b.config.getIdFromElem(c)),d},"")},e.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&b[this.config.restangularFields.what]&&(c+="/"+b[this.config.restangularFields.what]),c},b.urlCreatorFactory.path=e};var b={};a.init(this,b),this.$get=["$resource","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(D,a,b)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,G)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),n(d),f.transformElem(d,!0,c,G)}function r(a){var b={};return a&&(b[f.restangularFields.what]=a),b}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=r(a),h=this,i=d.defer(),k="getList",l=H.fetchUrl(this,g),m=a||h[f.restangularFields.route],n=_.extend(g,b);return f.requestInterceptor(null,k,m,l),H.resource(this,c,e,n).getList(n,function(b){var c=f.responseExtractor(b,k,m,l),d=_.map(c,function(b){return h[f.restangularFields.restangularCollection]?p(h[f.restangularFields.parentResource],b,h[f.restangularFields.route]):p(h,b,a)});d=_.extend(c,d),h[f.restangularFields.restangularCollection]?i.resolve(q(null,d,h[f.restangularFields.route])):i.resolve(q(h,d,a))},function(a){f.errorInterceptor(a),i.reject(a)}),j(i.promise,!0)}function u(a,b,e,g){var h=this,i=d.defer(),k=b||{},l=e||this,n=k[f.restangularFields.what]||this[f.restangularFields.route],o=H.fetchUrl(this,k),q=e||m(this);q=f.requestInterceptor(q,a,n,o);var r=function(b){var c=f.responseExtractor(b,a,n,o)||l;"post"!==a||h[f.restangularFields.restangularCollection]?i.resolve(p(h[f.restangularFields.parentResource],c,h[f.restangularFields.route])):i.resolve(p(h,c,k[f.restangularFields.what]))},s=function(a){f.errorInterceptor(a),i.reject(a)},t=a,u=_.extend({},g),v=f.isOverridenMethod(a);return v&&(t="post",u=_.extend(u,{"X-HTTP-Method-Override":a})),f.isSafe(a)?v?H.resource(this,c,u,k)[t](k,{},r,s):H.resource(this,c,u,k)[t](k,r,s):H.resource(this,c,u,k)[t](k,q,r,s),j(i.promise)}function v(a,b){return _.bind(u,this)("get",a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",a,void 0,b)}function x(a,b){return _.bind(u,this)("put",a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",_.extend(r(a),c),b,d)}function z(a,b){return _.bind(u,this)("head",a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",a,void 0,b)}function B(a,b){return _.bind(u,this)("options",a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,_.extend(r(b),c),e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),G.copy=_.bind(o,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(p,G),G.restangularizeCollection=_.bind(q,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 6f7d77997fef34c52bb9df0e4e235db5b614a65a..9e751de392781aa167196589db808d1016be850b 100644 GIT binary patch delta 539 zcmX@Jo$1ytCf)#VW)?065Lm!^Wg@QvACPjomJ}R#vXp`0Wa&ifY$hXv$-Sj3HU}^s zWZkU8Zp}D(o;dsD18f|!sfj76Ma2rX3d#9-X_@JIDXD3Rr8y-YVDZW4+0`T=Opuba z(!Au7%=|o!42WzZr|{(S0$_7^;N}43COdK|PPStb-dx2YtTb zo=c6pxx-S8fx%L3vP@|{(07}AOJ^}nwys!ZhT?%@+a#FbP-AOqs%v!;^@>wVTu^-a zzFdM8?1#*uK(fCL$llD_&LYALjJU}>vklN9aI)8I hV+By0BD~GOAP$aj7$I9WS)o*N^0wImY~6D}f&c`{yU_pu delta 315 zcmcb$i|NdECf)#VW)?065O^~4>_lD#J|N{3q}?%jLkR=JhLVZa*-VDU8&_nqO+KhA z&a6;Vvsr-MhHnO;e_|9#(kss_$?zyCDR4`=LCvrAPW=j4B#>@2C;wkeb6YpG1W+w97yGdZ%QpD}sz%a%eQ8QlsZ&$bo=NyoNw zAi1**#MW&u1(J)~D}khJ2avsaatDhDGtfbkXU#D{^W@|kbBq-*-3ksBD8W(+bh#$m I-&r6&091l;Jpcdz diff --git a/src/restangular.js b/src/restangular.js index e433decb..394db47f 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -37,7 +37,7 @@ module.provider('Restangular', function() { config.defaultHttpFields = values; } - config.withHttpDefaults = config.withHttpDefaults || function(obj) { + config.withHttpDefaults = function(obj) { return _.defaults(obj, config.defaultHttpFields); } @@ -46,6 +46,11 @@ module.provider('Restangular', function() { config.defaultRequestParams = values; } + config.defaultHeaders = config.defaultHeaders || {}; + object.setDefaultHeaders = function(headers) { + config.defaultHeaders = headers; + } + /** * Method overriders will set which methods are sent via POST with an X-HTTP-Method-Override **/ @@ -252,11 +257,15 @@ module.provider('Restangular', function() { return parents.reverse(); } - BaseCreator.prototype.resource = function(current, $resource, headers, params) { + BaseCreator.prototype.resource = function(current, $resource, callHeaders, params) { + var url = this.base(current); url += params[this.config.restangularFields.what] ? ("/:" + this.config.restangularFields.what) : ''; url += (this.config.suffix || ''); + + var headers = _.defaults(callHeaders, this.config.defaultHeaders); + return $resource(url, {}, { getList: this.config.withHttpDefaults({method: 'GET', params: this.config.defaultRequestParams, From 29abcd19079065107c66476e9a229dc8763515ca Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Thu, 20 Jun 2013 00:46:25 -0300 Subject: [PATCH 006/441] v0.8.4 --- CHANGELOG.md | 4 ++++ bower.json | 2 +- dist/restangular.js | 2 +- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 40282 -> 40282 bytes package.json | 2 +- 6 files changed, 8 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 753380a4..956bb2c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +#0.8.4 +* Fixed bug with defaultHttpFields for scoped configuration +* Added `defaultHeaders` + #0.8.3 * Fixed bug with URLHandler. Now it uses local configuration as well * Added error interceptor diff --git a/bower.json b/bower.json index 08cc58c6..fdc7e0a8 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "0.8.3", + "version": "0.8.4", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { diff --git a/dist/restangular.js b/dist/restangular.js index b2da0c1f..9bd5c6e7 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.3 - 2013-06-20 + * @version v0.8.4 - 2013-06-20 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 4c4e9a2f..735cebd1 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.3 - 2013-06-20 + * @version v0.8.4 - 2013-06-20 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.zip b/dist/restangular.zip index 9e751de392781aa167196589db808d1016be850b..6a62f1ec43d5f0692d121dfdde85ddfe55513898 100644 GIT binary patch delta 94 zcmcb$i|N)bChh=lW)?065ZE=5TZv;A>lLT70qMmPO;Z_7HqP!T1&iF_Oj|!$zbuo{ fWa8|toBhf?RT+0po-xM=u6**PIhF{O!gJjLK7b^2 delta 94 zcmcb$i|N)bChh=lW)?065LhsgTZv-<>lLSKNx^{=O;Z_-H_q-U1&gG{-P|!*zbuo{ fc;f7>oBhf?RT&pdo-xM=u6**PIhF{O!gJjLE8-+n diff --git a/package.json b/package.json index 1c3f49c8..ac0fb440 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "restangular", "description": "Restfull Resources service for AngularJS apps", - "version": "0.8.3", + "version": "0.8.4", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", "author": "Martin Gontovnikas ", From dc2f29c9657f4e503562d3a04351f455b31ab8a0 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Thu, 20 Jun 2013 01:42:38 -0300 Subject: [PATCH 007/441] Removed $resource completely. All test pass and I've tested this and this is working, but it needs some more testing as it's a HUGE refactor. Please anyone who can test this out :) Fixes #97 --- dist/restangular.js | 140 ++++++++++++++++++++++------------------ dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 40282 -> 39998 bytes src/restangular.js | 140 ++++++++++++++++++++++------------------ test/restangularSpec.js | 23 ++++--- 5 files changed, 170 insertions(+), 135 deletions(-) diff --git a/dist/restangular.js b/dist/restangular.js index 9bd5c6e7..a1680f74 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -7,7 +7,7 @@ */ (function(){ -var module = angular.module('restangular', ['ngResource']); +var module = angular.module('restangular', []); module.provider('Restangular', function() { // Configuration @@ -18,7 +18,7 @@ module.provider('Restangular', function() { */ var safeMethods= ["get", "head", "options", "trace"]; config.isSafe = function(operation) { - return _.contains(safeMethods, operation); + return _.contains(safeMethods, operation.toLowerCase()); } /** * This is the BaseURL to be used with Restangular @@ -102,8 +102,7 @@ module.provider('Restangular', function() { id: "id", route: "route", parentResource: "parentResource", - restangularCollection: "restangularCollection", - what: "restangularWhat" + restangularCollection: "restangularCollection" } object.setRestangularFields = function(resFields) { config.restangularFields = @@ -264,59 +263,83 @@ module.provider('Restangular', function() { return parents.reverse(); } - BaseCreator.prototype.resource = function(current, $resource, callHeaders, params) { + function RestangularResource($http, url, configurer) { + var resource = {}; + _.each(_.keys(configurer), function(key) { + var value = configurer[key]; + + // We don't want the ? if no params are there + if (_.isEmpty(value.params)) { + delete value.params; + } + + if (config.isSafe(value.method)) { + + resource[key] = function() { + return $http(_.extend(value, { + url: url + })); + } + + } else { + + resource[key] = function(data) { + return $http(_.extend(value, { + url: url, + data: data + })); + } + + } + }); + + return resource; + } + + BaseCreator.prototype.resource = function(current, $http, callHeaders, callParams, what) { + + var params = _.defaults(callParams, this.config.defaultRequestParams); + var headers = _.defaults(callHeaders, this.config.defaultHeaders); var url = this.base(current); - url += params[this.config.restangularFields.what] ? - ("/:" + this.config.restangularFields.what) : ''; + url += what ? ("/" + what): ''; url += (this.config.suffix || ''); - var headers = _.defaults(callHeaders, this.config.defaultHeaders); - - return $resource(url, {}, { + return RestangularResource($http, url, { getList: this.config.withHttpDefaults({method: 'GET', - params: this.config.defaultRequestParams, - isArray: this.config.listTypeIsArray, + params: params, headers: headers || {}}), get: this.config.withHttpDefaults({method: 'GET', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}), put: this.config.withHttpDefaults({method: 'PUT', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}), post: this.config.withHttpDefaults({method: 'POST', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}), remove: this.config.withHttpDefaults({method: 'DELETE', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}), head: this.config.withHttpDefaults({method: 'HEAD', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}), trace: this.config.withHttpDefaults({method: 'TRACE', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}), options: this.config.withHttpDefaults({method: 'OPTIONS', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}), patch: this.config.withHttpDefaults({method: 'PATCH', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}) }); } @@ -346,10 +369,10 @@ module.provider('Restangular', function() { - Path.prototype.fetchUrl = function(current, params) { + Path.prototype.fetchUrl = function(current, what) { var baseUrl = this.base(current); - if (params && params[this.config.restangularFields.what]) { - baseUrl += "/" + params[this.config.restangularFields.what]; + if (what) { + baseUrl += "/" + what; } return baseUrl; } @@ -367,7 +390,7 @@ module.provider('Restangular', function() { - this.$get = ['$resource', '$q', function($resource, $q) { + this.$get = ['$http', '$q', function($http, $q) { function createServiceForConfiguration(config) { var service = {}; @@ -494,14 +517,6 @@ module.provider('Restangular', function() { return config.transformElem(localElem, true, route, service); } - function whatObject(what) { - var search = {}; - if (what) { - search[config.restangularFields.what] = what; - } - return search; - } - function putElementFunction(idx, params, headers) { var __this = this; var elemToPut = this[idx]; @@ -518,18 +533,18 @@ module.provider('Restangular', function() { } - function fetchFunction(what, params, headers) { - var search = whatObject(what); + function fetchFunction(what, reqParams, headers) { var __this = this; var deferred = $q.defer(); var operation = 'getList'; - var url = urlHandler.fetchUrl(this, search); + var url = urlHandler.fetchUrl(this, what); var whatFetched = what || __this[config.restangularFields.route]; - var reqParams = _.extend(search, params); + config.requestInterceptor(null, operation, whatFetched, url) - urlHandler.resource(this, $resource, headers, reqParams).getList(reqParams, function(resData) { + urlHandler.resource(this, $http, headers, reqParams, what).getList().then(function(response) { + var resData = response.data; var data = config.responseExtractor(resData, operation, whatFetched, url); var processedData = _.map(data, function(elem) { if (!__this[config.restangularFields.restangularCollection]) { @@ -555,22 +570,23 @@ module.provider('Restangular', function() { return restangularizePromise(deferred.promise, true); } - function elemFunction(operation, params, obj, headers) { + function elemFunction(operation, what, params, obj, headers) { var __this = this; var deferred = $q.defer(); var resParams = params || {}; var resObj = obj || this; - var route = resParams[config.restangularFields.what] || this[config.restangularFields.route]; - var fetchUrl = urlHandler.fetchUrl(this, resParams); + var route = what || this[config.restangularFields.route]; + var fetchUrl = urlHandler.fetchUrl(this, what); var callObj = obj || stripRestangular(this); callObj = config.requestInterceptor(callObj, operation, route, fetchUrl) - var okCallback = function(resData) { + var okCallback = function(response) { + var resData = response.data; var elem = config.responseExtractor(resData, operation, route, fetchUrl) || resObj; if (operation === "post" && !__this[config.restangularFields.restangularCollection]) { - deferred.resolve(restangularizeElem(__this, elem, resParams[config.restangularFields.what])); + deferred.resolve(restangularizeElem(__this, elem, what)); } else { deferred.resolve(restangularizeElem(__this[config.restangularFields.parentResource], elem, __this[config.restangularFields.route])); } @@ -592,51 +608,51 @@ module.provider('Restangular', function() { if (config.isSafe(operation)) { if (isOverrideOperation) { - urlHandler.resource(this, $resource, callHeaders, resParams)[callOperation](resParams, {}, okCallback, errorCallback); + urlHandler.resource(this, $http, callHeaders, resParams, what)[callOperation]({}).then(okCallback, errorCallback); } else { - urlHandler.resource(this, $resource, callHeaders, resParams)[callOperation](resParams, okCallback, errorCallback); + urlHandler.resource(this, $http, callHeaders, resParams, what)[callOperation]().then(okCallback, errorCallback); } } else { - urlHandler.resource(this, $resource, callHeaders, resParams)[callOperation](resParams, callObj, okCallback, errorCallback); + urlHandler.resource(this, $http, callHeaders, resParams, what)[callOperation](callObj).then(okCallback, errorCallback); } return restangularizePromise(deferred.promise); } function getFunction(params, headers) { - return _.bind(elemFunction, this)("get", params, undefined, headers); + return _.bind(elemFunction, this)("get", undefined, params, undefined, headers); } function deleteFunction(params, headers) { - return _.bind(elemFunction, this)("remove", params, undefined, headers); + return _.bind(elemFunction, this)("remove", undefined, params, undefined, headers); } function putFunction(params, headers) { - return _.bind(elemFunction, this)("put", params, undefined, headers); + return _.bind(elemFunction, this)("put", undefined, params, undefined, headers); } function postFunction(what, elem, params, headers) { - return _.bind(elemFunction, this)("post", _.extend(whatObject(what), params), elem, headers); + return _.bind(elemFunction, this)("post", what, params, elem, headers); } function headFunction(params, headers) { - return _.bind(elemFunction, this)("head", params, undefined, headers); + return _.bind(elemFunction, this)("head", undefined, params, undefined, headers); } function traceFunction(params, headers) { - return _.bind(elemFunction, this)("trace", params, undefined, headers); + return _.bind(elemFunction, this)("trace", undefined, params, undefined, headers); } function optionsFunction(params, headers) { - return _.bind(elemFunction, this)("options", params, undefined, headers); + return _.bind(elemFunction, this)("options", undefined, params, undefined, headers); } function patchFunction(params, headers) { - return _.bind(elemFunction, this)("patch", params, undefined, headers); + return _.bind(elemFunction, this)("patch", undefined, params, undefined, headers); } function customFunction(operation, path, params, headers, elem) { - return _.bind(elemFunction, this)(operation, _.extend(whatObject(path), params), elem, headers); + return _.bind(elemFunction, this)(operation, path, params, elem, headers); } function addRestangularMethodFunction(name, operation, path, defaultParams, defaultHeaders, defaultElem) { diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 735cebd1..70bbaf5e 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -5,4 +5,4 @@ * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",["ngResource"]);a.provider("Restangular",function(){var a={};a.init=function(a,b){var c=["get","head","options","trace"];b.isSafe=function(a){return _.contains(c,a)},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",what:"restangularWhat"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},b.listTypeIsArray=_.isUndefined(b.listTypeIsArray)?!0:b.listTypeIsArray,a.setListTypeIsArray=function(a){b.listTypeIsArray=a},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var d=function(){};d.prototype.setConfig=function(a){this.config=a},d.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},d.prototype.resource=function(a,b,c,d){var e=this.base(a);e+=d[this.config.restangularFields.what]?"/:"+this.config.restangularFields.what:"",e+=this.config.suffix||"";var f=_.defaults(c,this.config.defaultHeaders);return b(e,{},{getList:this.config.withHttpDefaults({method:"GET",params:this.config.defaultRequestParams,isArray:this.config.listTypeIsArray,headers:f||{}}),get:this.config.withHttpDefaults({method:"GET",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}}),put:this.config.withHttpDefaults({method:"PUT",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}}),post:this.config.withHttpDefaults({method:"POST",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:this.config.defaultRequestParams,isArray:!1,headers:f||{}})})};var e=function(){};e.prototype=new d,e.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];return c[b.config.restangularFields.restangularCollection]||(d+="/"+b.config.getIdFromElem(c)),d},"")},e.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&b[this.config.restangularFields.what]&&(c+="/"+b[this.config.restangularFields.what]),c},b.urlCreatorFactory.path=e};var b={};a.init(this,b),this.$get=["$resource","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(D,a,b)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,G)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),n(d),f.transformElem(d,!0,c,G)}function r(a){var b={};return a&&(b[f.restangularFields.what]=a),b}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=r(a),h=this,i=d.defer(),k="getList",l=H.fetchUrl(this,g),m=a||h[f.restangularFields.route],n=_.extend(g,b);return f.requestInterceptor(null,k,m,l),H.resource(this,c,e,n).getList(n,function(b){var c=f.responseExtractor(b,k,m,l),d=_.map(c,function(b){return h[f.restangularFields.restangularCollection]?p(h[f.restangularFields.parentResource],b,h[f.restangularFields.route]):p(h,b,a)});d=_.extend(c,d),h[f.restangularFields.restangularCollection]?i.resolve(q(null,d,h[f.restangularFields.route])):i.resolve(q(h,d,a))},function(a){f.errorInterceptor(a),i.reject(a)}),j(i.promise,!0)}function u(a,b,e,g){var h=this,i=d.defer(),k=b||{},l=e||this,n=k[f.restangularFields.what]||this[f.restangularFields.route],o=H.fetchUrl(this,k),q=e||m(this);q=f.requestInterceptor(q,a,n,o);var r=function(b){var c=f.responseExtractor(b,a,n,o)||l;"post"!==a||h[f.restangularFields.restangularCollection]?i.resolve(p(h[f.restangularFields.parentResource],c,h[f.restangularFields.route])):i.resolve(p(h,c,k[f.restangularFields.what]))},s=function(a){f.errorInterceptor(a),i.reject(a)},t=a,u=_.extend({},g),v=f.isOverridenMethod(a);return v&&(t="post",u=_.extend(u,{"X-HTTP-Method-Override":a})),f.isSafe(a)?v?H.resource(this,c,u,k)[t](k,{},r,s):H.resource(this,c,u,k)[t](k,r,s):H.resource(this,c,u,k)[t](k,q,r,s),j(i.promise)}function v(a,b){return _.bind(u,this)("get",a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",a,void 0,b)}function x(a,b){return _.bind(u,this)("put",a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",_.extend(r(a),c),b,d)}function z(a,b){return _.bind(u,this)("head",a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",a,void 0,b)}function B(a,b){return _.bind(u,this)("options",a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,_.extend(r(b),c),e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),G.copy=_.bind(o,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(p,G),G.restangularizeCollection=_.bind(q,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},b.listTypeIsArray=_.isUndefined(b.listTypeIsArray)?!0:b.listTypeIsArray,a.setListTypeIsArray=function(a){b.listTypeIsArray=a},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e,this.config.defaultRequestParams),h=_.defaults(d,this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];return c[b.config.restangularFields.restangularCollection]||(d+="/"+b.config.getIdFromElem(c)),d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(G.fetchUrl,G,b),b.addRestangularMethod=_.bind(D,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(C,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(C,a,b)})}),a.customGETLIST=_.bind(s,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(u,d),d.getList=_.bind(s,d),d.put=_.bind(w,d),d.post=_.bind(x,d),d.remove=_.bind(v,d),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,F)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(x,d,null),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.putElement=_.bind(r,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.getList=_.bind(s,d,null),n(d),f.transformElem(d,!0,c,F)}function r(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function s(a,b,e){var g=this,h=d.defer(),i="getList",k=G.fetchUrl(this,a),l=a||g[f.restangularFields.route];return f.requestInterceptor(null,i,l,k),G.resource(this,c,e,b,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?p(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):p(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?h.resolve(q(null,e,g[f.restangularFields.route])):h.resolve(q(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function t(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},n=g||this,o=b||this[f.restangularFields.route],q=G.fetchUrl(this,b),r=g||m(this);r=f.requestInterceptor(r,a,o,q);var s=function(c){var d=c.data,e=f.responseExtractor(d,a,o,q)||n;"post"!==a||i[f.restangularFields.restangularCollection]?k.resolve(p(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):k.resolve(p(i,e,b))},t=function(a){f.errorInterceptor(a),k.reject(a)},u=a,v=_.extend({},h),w=f.isOverridenMethod(a);return w&&(u="post",v=_.extend(v,{"X-HTTP-Method-Override":a})),f.isSafe(a)?w?G.resource(this,c,v,l,b)[u]({}).then(s,t):G.resource(this,c,v,l,b)[u]().then(s,t):G.resource(this,c,v,l,b)[u](r).then(s,t),j(k.promise)}function u(a,b){return _.bind(t,this)("get",void 0,a,void 0,b)}function v(a,b){return _.bind(t,this)("remove",void 0,a,void 0,b)}function w(a,b){return _.bind(t,this)("put",void 0,a,void 0,b)}function x(a,b,c,d){return _.bind(t,this)("post",a,c,b,d)}function y(a,b){return _.bind(t,this)("head",void 0,a,void 0,b)}function z(a,b){return _.bind(t,this)("trace",void 0,a,void 0,b)}function A(a,b){return _.bind(t,this)("options",void 0,a,void 0,b)}function B(a,b){return _.bind(t,this)("patch",void 0,a,void 0,b)}function C(a,b,c,d,e){return _.bind(t,this)(a,b,c,e,d)}function D(a,b,c,d,e,f){var g;g="getList"===b?_.bind(s,this,c):_.bind(C,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function E(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var F={},G=new f.urlCreatorFactory[f.urlCreator];return G.setConfig(f),F.copy=_.bind(o,F),F.withConfig=_.bind(E,F),F.one=_.bind(h,F,null),F.all=_.bind(i,F,null),F.restangularizeElement=_.bind(p,F),F.restangularizeCollection=_.bind(q,F),F}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 6a62f1ec43d5f0692d121dfdde85ddfe55513898..67e7192db815b7a4379f1f42eff23a0cd861cc71 100644 GIT binary patch delta 3997 zcmb7HU2GKB74~8qu<;TWdu=aZd%R$KhP@u!g%+~QVEI1?)EGk`u50Ysox4BwdS-TJ zb{EI%;?N}gRSo8l@UH~rAyOX_(tSvq2TEI2;-OX3st;*ZsZ~`ajZ~@ht(A(>duMiL zccFmlm1plgKlh&b&N<(``-e}~-2Ks-y77aRRkaoLZ`{3F*S>Mw{ky@y4}W^JHB(X1 zn)xX7qAUNl>({Q0yrCRYvRE4ubxL-D(n(PxLnW<6FuNme7%F1YS`slZsci%0#JXxz1-JKmVPnHOW`>`~i#i)o zU-YM6>O3u4a}6Nbogkv0a}xr;7)fnT>+->Mz>|KfQ`5!aU|R=aPe?GUBRsta4-Xf?yqkH zb+DFd;N3mzye2s843AG5SeC315Qu|5m_4w5J;5wUfdkLjR;a1-z(t`JdU1p4PB-{; zvd!LTOW8&QBL_eU#FtzC-yK)gtuV`1*Gi%x1{wN%Vi0%So1njQGxSb82g-D9A-BKb z4sW+I9}$zu7qBQ{O-Br!jGMVYOg1hW;Av_gui&BSh3^d3G|cc4j*97|LF&P_g;bys z-tBXPxUb$coCwUC-|?M&&2$x#X4c>1X9A45C>Lb9x?p9e584CW6z8^Q6ehH9Z-T!B zj=}}C75?7W1HVV(&iLc*;`l9o!jY$YjydDW-lF{ZK6{-rj^4G)mNn;pxof(r%6xZM zM>CA={Tf`J*apAY>#>9bodF0u|8Oe>uM06FJT{kb*x>I5dC z_{{2@{YEuhpZN@KHTs^lT>j$h1{ZudSq-lWK2qN8urln)KNr4VSw(|~KjCJ^DjaT# zmdA@K){5qcCXKoyxE4b%ZVqRBG zS|(+ikg)`#iI?DS@!2xThh?)KV3Hf5cTTILRe%cI1TAtKw9SzwpRa+3bCYE*2v+8e z$0R=3lbm@(dN28?-HC-;b*gB@?Tzv+a_#!fl=J_+d+y8oJ1Q#Ze^UhnZuwS^{s+F9 z?S=E%kyCcfF%eco5hQU-8Bt@fu(TY~u#whe!rNGk#0hbKG*!u?#=W z6q%eBrXI^2!pronBw@-=s^5?Nv^&U`qQd9dJst^(<%eLNIeDQf|Fhg*tKs(9EpYF2 zrwhXur!SLd?z`<RWUy_Qv4j+3TeN723{8wUX0KQ>MWyVd+m-{CRCS9aa$7hEf4=yFYZSQE zcsJP+$?0U02KUS@;O=U3Kzr&&<@=B~Cnz*s>Tr*8%XTst4Ze5joiUwsc^F~4acP;6 zYL#eNVvQx`D9{d}=Yt>33q|l*(^BM6QV?^w7`*y6Ijav;!|b{BBx84v`wk{h63ugH zjJK~SmP>^6N*IZc9XobhEa_reHW9)Kv}KVbMB(;qeOCk(R-|Arh$<@;iKp24G!j&) zvh>>vr!H@H*|Du{2@QNa`NVv2jSf)!0v_6kJ4l!+NQN*~bLPBEU%j(|$p+5XJOC=QGO_i81kd^+m&0Mg|hUS`LWI*qg z?c1r!1_`AF5oL-=APB@cl!eTdHea^0lT8cO_N6u%_}~gUmF<7Lq%x$|!rWB4*vT%?;(@rZfB$@TjQvzE^=(wbp(s1uuLxW)wJI7jQN=8XYOfUT7Y9oB>s<+8e zTD;;%CHhNOy+vn2PNmAwNwbK|lh`?cO|ElRH1k9f7a_$al|;2jqw+dtlvqkvhC|o9 zjgHo&F-NUj3p6{b0-HHX`bs}3^(FU=NW4_NcgPN!Qp^7io3;iegVKnH;g#!w%_Jq1 zh9X?B!0JQr@%0<75jb)qw04x-M9>&qzQNCp@j5n!%%6|s>VZbdk*Y4*^s1myD#|8| zxMgB1Ml6LQJER>)qXqUI<;m^RHcS-7fNnBXbUhfqx!oFMZ!&Af-Ei$@-y=Vy;j^2& X+8)1WnLoS>4-IzS+PPM_L8t!(H|%@B delta 3937 zcma)9ZA@F&8ODjtSAjqY1_C74=EL{KCkB#cUF_UZ3J$Do64ExI4FYm)AAex`+T451 z$FP@14at%&gz#ofTB0`Der!LsWs(0(s9H8@Qq>>RHnrNMsjb>=l_vGa+CS0$RM|QA z%aBqROPK5T>%8ZA&ifqucfZ~CkF{-8BhPNPR+iA$n(bPZqh`(a!P9>liOBC|N=n|# z-18l`RJp{+^H@%0q#$f!l}L;Crq0klJm_-`f6MHHRvhM_#j0LGdz93CoHg zMluOO8YLDde9_zjM{Sk)>bkWi_}pcOy`J4|BuXuhn4pkI3}YdLB^fbkK@yTOeCpo` zznQFqGY%^p@9r(t%};TA%IGTNOdmKp>dRSYx7W$I8R+MBmr@7E!1eBD)U?k%XW%dH z@;YN7HX|hvvyek@r@awcdR~N&&ol71Cz@(va=#=A^Ik@Y#$*qOZFcx_{}8;>Gh&47 zFhjyZLdFQrxtrkX!6x|qfkt?_cWZGEdY|7?y`StqwWYZ49@t8~_?BwTJ@L|(;@S?H zux*A({_4Su)gX&6qr2h003k9jMR$)Awm(B`tG2FolB(oba}&y*&F^ z1$;7Lhhtu*oMB`vNWmyr_+9#`;^BwhM))LRrz@B0?tcHF{2yOokfyR;bOc zoNiuuk%RQWKByQyYGmD;Xa;$7geJ60czQ%V*9^~0dhncr#Sp7iH&1-em>tsAGWd8j z)L+Ap93*p4Py_<%F1m95{gxOC%&Xid;R?;}kTLL?+^M9YR>wOB=S8q6F=Zy^@GTI8vh z+0?67N~dJ4)a-@oBBicg7%1ZX=t5r+uj^ue5wCpFPrZ(!O$rJTFS_9e7i(yATaoA- z2k*Yhl=C8?cvlx2bo0(`r&~4Z3Vr3$ZW8*-ORmD$ z{r!?uHS7sv(!oh`tq#M<%T9|wKX-X-yJZkQxRNFBCzc!*1>~jwot+^^1%(XZBAf?e zL;w}dn$9SOWlpyc^bOOzW|D9+HG>V~tY)PA8>Sy~*wOSPw|1j$C|)0&x# zSTJhX2B3O**fIpCmZO$=xWC+Zwn#zJv7Zb+7R@eYeWfidq($l)ZY)orKw>75;E>1? zsKOovPF~yDF~sGJL1ZK{Tk5z4crudukO*B}aDS<>K_!nDI20%($S`y5?PCfnpa8;J zYJ{g%P*fdQ6yrm5_^`xsD9$_emYgWT7no(~xS; z00*-x&hj`)BC>;FxU*7!S}fdCA~H6?2DCnceAq+ogES!p`{yWUN=jk_NUuOiO$uo? zxFJ#BGVQ@_?Mt&!_`{ORqP6sJskF^YOk}G9m*af2g5DmLDWoPf^u_3^sl*Isr&$U& zLEX%+ueph(Qgn0H=;08Yz!V=vp<>9P$j^qlxzxUfNBW=6KAt3h$0^+ z9XDv-G|1K4du11evLp31xZ@m}rfEqPea<({!`YRFW79}LB1&{uWTRq--|f zb5dDzI(UOhcg;FPG(bDa1z|!`zaA2bZV;(k(3G9ya!BUEaoyRz9wemj0?HKdCm4|9 zGXp)Z?`fSO`l9e!8|z~-Xu$~+6?QoHdi~j%zG0On`rAW0enFH$ac)c*XXE5bKoXKU zZ?Twf4VYGIP&PejDV2=LxG-pdZ`i9dh*HL}bSRwg*Bf^D#f^qq)2gWvb+oi`3;My- zRm}_{Dxszxo>vcxdR=}~DCGs2M^+uuAQ@(I22b5&YRr;U@U(V*db44NX;wu~vwwE8 zq0Y3YG&xc|9RswBZ*G=~p&IBPG}@)Av3bM7`d$MZBE4cVW(Do>!^9iz#}ySt;`Qp- z48rOgtCl11jZt@IO&tuouzY>->+edNb5 cyt8^>&)2_dsXw0ew>GG`wYT)OTlC}q0jkh$2><{9 diff --git a/src/restangular.js b/src/restangular.js index 394db47f..e43f2960 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -1,6 +1,6 @@ (function(){ -var module = angular.module('restangular', ['ngResource']); +var module = angular.module('restangular', []); module.provider('Restangular', function() { // Configuration @@ -11,7 +11,7 @@ module.provider('Restangular', function() { */ var safeMethods= ["get", "head", "options", "trace"]; config.isSafe = function(operation) { - return _.contains(safeMethods, operation); + return _.contains(safeMethods, operation.toLowerCase()); } /** * This is the BaseURL to be used with Restangular @@ -95,8 +95,7 @@ module.provider('Restangular', function() { id: "id", route: "route", parentResource: "parentResource", - restangularCollection: "restangularCollection", - what: "restangularWhat" + restangularCollection: "restangularCollection" } object.setRestangularFields = function(resFields) { config.restangularFields = @@ -257,59 +256,83 @@ module.provider('Restangular', function() { return parents.reverse(); } - BaseCreator.prototype.resource = function(current, $resource, callHeaders, params) { + function RestangularResource($http, url, configurer) { + var resource = {}; + _.each(_.keys(configurer), function(key) { + var value = configurer[key]; + + // We don't want the ? if no params are there + if (_.isEmpty(value.params)) { + delete value.params; + } + + if (config.isSafe(value.method)) { + + resource[key] = function() { + return $http(_.extend(value, { + url: url + })); + } + + } else { + + resource[key] = function(data) { + return $http(_.extend(value, { + url: url, + data: data + })); + } + + } + }); + + return resource; + } + + BaseCreator.prototype.resource = function(current, $http, callHeaders, callParams, what) { + + var params = _.defaults(callParams, this.config.defaultRequestParams); + var headers = _.defaults(callHeaders, this.config.defaultHeaders); var url = this.base(current); - url += params[this.config.restangularFields.what] ? - ("/:" + this.config.restangularFields.what) : ''; + url += what ? ("/" + what): ''; url += (this.config.suffix || ''); - var headers = _.defaults(callHeaders, this.config.defaultHeaders); - - return $resource(url, {}, { + return RestangularResource($http, url, { getList: this.config.withHttpDefaults({method: 'GET', - params: this.config.defaultRequestParams, - isArray: this.config.listTypeIsArray, + params: params, headers: headers || {}}), get: this.config.withHttpDefaults({method: 'GET', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}), put: this.config.withHttpDefaults({method: 'PUT', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}), post: this.config.withHttpDefaults({method: 'POST', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}), remove: this.config.withHttpDefaults({method: 'DELETE', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}), head: this.config.withHttpDefaults({method: 'HEAD', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}), trace: this.config.withHttpDefaults({method: 'TRACE', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}), options: this.config.withHttpDefaults({method: 'OPTIONS', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}), patch: this.config.withHttpDefaults({method: 'PATCH', - params: this.config.defaultRequestParams, - isArray: false, + params: params, headers: headers || {}}) }); } @@ -339,10 +362,10 @@ module.provider('Restangular', function() { - Path.prototype.fetchUrl = function(current, params) { + Path.prototype.fetchUrl = function(current, what) { var baseUrl = this.base(current); - if (params && params[this.config.restangularFields.what]) { - baseUrl += "/" + params[this.config.restangularFields.what]; + if (what) { + baseUrl += "/" + what; } return baseUrl; } @@ -360,7 +383,7 @@ module.provider('Restangular', function() { - this.$get = ['$resource', '$q', function($resource, $q) { + this.$get = ['$http', '$q', function($http, $q) { function createServiceForConfiguration(config) { var service = {}; @@ -487,14 +510,6 @@ module.provider('Restangular', function() { return config.transformElem(localElem, true, route, service); } - function whatObject(what) { - var search = {}; - if (what) { - search[config.restangularFields.what] = what; - } - return search; - } - function putElementFunction(idx, params, headers) { var __this = this; var elemToPut = this[idx]; @@ -511,18 +526,18 @@ module.provider('Restangular', function() { } - function fetchFunction(what, params, headers) { - var search = whatObject(what); + function fetchFunction(what, reqParams, headers) { var __this = this; var deferred = $q.defer(); var operation = 'getList'; - var url = urlHandler.fetchUrl(this, search); + var url = urlHandler.fetchUrl(this, what); var whatFetched = what || __this[config.restangularFields.route]; - var reqParams = _.extend(search, params); + config.requestInterceptor(null, operation, whatFetched, url) - urlHandler.resource(this, $resource, headers, reqParams).getList(reqParams, function(resData) { + urlHandler.resource(this, $http, headers, reqParams, what).getList().then(function(response) { + var resData = response.data; var data = config.responseExtractor(resData, operation, whatFetched, url); var processedData = _.map(data, function(elem) { if (!__this[config.restangularFields.restangularCollection]) { @@ -548,22 +563,23 @@ module.provider('Restangular', function() { return restangularizePromise(deferred.promise, true); } - function elemFunction(operation, params, obj, headers) { + function elemFunction(operation, what, params, obj, headers) { var __this = this; var deferred = $q.defer(); var resParams = params || {}; var resObj = obj || this; - var route = resParams[config.restangularFields.what] || this[config.restangularFields.route]; - var fetchUrl = urlHandler.fetchUrl(this, resParams); + var route = what || this[config.restangularFields.route]; + var fetchUrl = urlHandler.fetchUrl(this, what); var callObj = obj || stripRestangular(this); callObj = config.requestInterceptor(callObj, operation, route, fetchUrl) - var okCallback = function(resData) { + var okCallback = function(response) { + var resData = response.data; var elem = config.responseExtractor(resData, operation, route, fetchUrl) || resObj; if (operation === "post" && !__this[config.restangularFields.restangularCollection]) { - deferred.resolve(restangularizeElem(__this, elem, resParams[config.restangularFields.what])); + deferred.resolve(restangularizeElem(__this, elem, what)); } else { deferred.resolve(restangularizeElem(__this[config.restangularFields.parentResource], elem, __this[config.restangularFields.route])); } @@ -585,51 +601,51 @@ module.provider('Restangular', function() { if (config.isSafe(operation)) { if (isOverrideOperation) { - urlHandler.resource(this, $resource, callHeaders, resParams)[callOperation](resParams, {}, okCallback, errorCallback); + urlHandler.resource(this, $http, callHeaders, resParams, what)[callOperation]({}).then(okCallback, errorCallback); } else { - urlHandler.resource(this, $resource, callHeaders, resParams)[callOperation](resParams, okCallback, errorCallback); + urlHandler.resource(this, $http, callHeaders, resParams, what)[callOperation]().then(okCallback, errorCallback); } } else { - urlHandler.resource(this, $resource, callHeaders, resParams)[callOperation](resParams, callObj, okCallback, errorCallback); + urlHandler.resource(this, $http, callHeaders, resParams, what)[callOperation](callObj).then(okCallback, errorCallback); } return restangularizePromise(deferred.promise); } function getFunction(params, headers) { - return _.bind(elemFunction, this)("get", params, undefined, headers); + return _.bind(elemFunction, this)("get", undefined, params, undefined, headers); } function deleteFunction(params, headers) { - return _.bind(elemFunction, this)("remove", params, undefined, headers); + return _.bind(elemFunction, this)("remove", undefined, params, undefined, headers); } function putFunction(params, headers) { - return _.bind(elemFunction, this)("put", params, undefined, headers); + return _.bind(elemFunction, this)("put", undefined, params, undefined, headers); } function postFunction(what, elem, params, headers) { - return _.bind(elemFunction, this)("post", _.extend(whatObject(what), params), elem, headers); + return _.bind(elemFunction, this)("post", what, params, elem, headers); } function headFunction(params, headers) { - return _.bind(elemFunction, this)("head", params, undefined, headers); + return _.bind(elemFunction, this)("head", undefined, params, undefined, headers); } function traceFunction(params, headers) { - return _.bind(elemFunction, this)("trace", params, undefined, headers); + return _.bind(elemFunction, this)("trace", undefined, params, undefined, headers); } function optionsFunction(params, headers) { - return _.bind(elemFunction, this)("options", params, undefined, headers); + return _.bind(elemFunction, this)("options", undefined, params, undefined, headers); } function patchFunction(params, headers) { - return _.bind(elemFunction, this)("patch", params, undefined, headers); + return _.bind(elemFunction, this)("patch", undefined, params, undefined, headers); } function customFunction(operation, path, params, headers, elem) { - return _.bind(elemFunction, this)(operation, _.extend(whatObject(path), params), elem, headers); + return _.bind(elemFunction, this)(operation, path, params, elem, headers); } function addRestangularMethodFunction(name, operation, path, defaultParams, defaultHeaders, defaultElem) { diff --git a/test/restangularSpec.js b/test/restangularSpec.js index 2b9268e8..e4d5187d 100644 --- a/test/restangularSpec.js +++ b/test/restangularSpec.js @@ -16,7 +16,6 @@ describe("Restangular", function() { // Remove all Restangular/AngularJS added methods in order to use Jasmine toEqual between the retrieve resource and the model function sanitizeRestangularOne(item) { return _.omit(item, "route", "parentResource", "getList", "get", "post", "put", "remove", "head", "trace", "options", "patch", - "$get", "$save", "$query", "$remove", "$delete", "$put", "$post", "$head", "$trace", "$options", "$patch", "$then", "$resolved", "restangularCollection", "customOperation", "customGET", "customPOST", "customPUT", "customDELETE", "customGETLIST", "$getList", "$resolved", "restangularCollection", "one", "all","doGET", "doPOST", "doPUT", "doDELETE", "doGETLIST", "addRestangularMethod", "getRestangularUrl"); @@ -57,7 +56,6 @@ describe("Restangular", function() { $httpBackend.whenPOST("/accounts").respond(function(method, url, data, headers) { var newData = angular.fromJson(data); newData.fromServer = true; - accountsModel.push(newData); return [201, JSON.stringify(newData), ""]; }); @@ -92,7 +90,7 @@ describe("Restangular", function() { describe("ALL", function() { it("getList() should return an array of items", function() { restangularAccounts.getList().then(function(accounts) { - expect(sanitizeRestangularAll(accounts)).toEqual(accountsModel); + expect(sanitizeRestangularAll(accounts)).toEqual(sanitizeRestangularAll(accountsModel)); }); $httpBackend.flush(); @@ -106,7 +104,7 @@ describe("Restangular", function() { it("Custom GET methods sohuld work", function() { restangularAccounts.customGETLIST("messages").then(function(msgs) { - expect(sanitizeRestangularAll(msgs)).toEqual(messages); + expect(sanitizeRestangularAll(msgs)).toEqual(sanitizeRestangularAll(messages)); }); $httpBackend.flush(); @@ -146,7 +144,8 @@ describe("Restangular", function() { restangularAccounts.getList().then(function(accounts) { var newTransaction = {id: 1, name: "Gonto"}; accounts[1].post('transactions', newTransaction).then(function(transaction) { - expect(sanitizeRestangularOne(transaction)).toEqual(newTransaction); + expect(sanitizeRestangularOne(transaction)) + .toEqual(sanitizeRestangularOne(newTransaction)); }); }); @@ -180,7 +179,8 @@ describe("Restangular", function() { describe("ONE", function() { it("get() should return a JSON item", function() { restangularAccount1.get().then(function(account) { - expect(sanitizeRestangularOne(account)).toEqual(accountsModel[1]); + expect(sanitizeRestangularOne(account)) + .toEqual(sanitizeRestangularOne(accountsModel[1])); }); $httpBackend.flush(); @@ -188,7 +188,8 @@ describe("Restangular", function() { it("Should make RequestLess connections with one", function() { restangularAccount1.one("transactions", 1).get().then(function(transaction) { - expect(sanitizeRestangularOne(transaction)).toEqual(accountsModel[1].transactions[1]); + expect(sanitizeRestangularOne(transaction)) + .toEqual(sanitizeRestangularOne(accountsModel[1].transactions[1])); }); $httpBackend.flush(); @@ -196,7 +197,8 @@ describe("Restangular", function() { it("Should make RequestLess connections with all", function() { restangularAccount1.all("transactions").getList().then(function(transactions) { - expect(sanitizeRestangularAll(transactions)).toEqual(accountsModel[1].transactions); + expect(sanitizeRestangularAll(transactions)) + .toEqual(sanitizeRestangularAll(accountsModel[1].transactions)); }); $httpBackend.flush(); @@ -205,7 +207,7 @@ describe("Restangular", function() { it("Custom GET methods should work", function() { restangularAccount1.customGET("message").then(function(msg) { - expect(sanitizeRestangularOne(msg)).toEqual(messages[0]); + expect(sanitizeRestangularOne(msg)).toEqual(sanitizeRestangularOne(messages[0])); }); $httpBackend.flush(); @@ -230,7 +232,8 @@ describe("Restangular", function() { it("should return an array when accessing a subvalue", function() { restangularAccount1.get().then(function(account) { account.getList("transactions").then(function(transactions) { - expect(sanitizeRestangularAll(transactions)).toEqual(accountsModel[1].transactions); + expect(sanitizeRestangularAll(transactions)) + .toEqual(sanitizeRestangularAll(accountsModel[1].transactions)); }); }); From fa4b5a1745ec74fd07f479ca9c13fa9798c34a51 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Thu, 20 Jun 2013 01:49:15 -0300 Subject: [PATCH 008/441] Updated README, and depracated listTypeIsArray --- CHANGELOG.md | 3 +++ README.md | 30 ++++++------------------------ bower.json | 3 +-- package.json | 2 +- src/restangular.js | 7 ++----- 5 files changed, 13 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 956bb2c7..1491b92b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +#0.8.5 +* Ditched the buggy `$resource` and using `$http` inside :D + #0.8.4 * Fixed bug with defaultHttpFields for scoped configuration * Added `defaultHeaders` diff --git a/README.md b/README.md index ac27b843..49b14143 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ You can download this by: #Dependencies -Restangular depends on Angular, Angular-Resources and (Underscore or Lodash). +Restangular depends on Angular and (Underscore or Lodash). **angular-resource is no longer needed, now this uses `$http` instead of `$resource*`* #Starter Guide @@ -271,7 +271,9 @@ The errorInterceptor is called whenever there's an error. It's a function that r #### listTypeIsArray -You can set in this property wether the `getList` method will return an Array or not. Most of the times, it will return an array, as it returns a collection of values. However, sometimes this method returns first some metadata and inside it has the array. So this can be used together with `responseExtractor` to get the real array. The default value is true. +We don't use `$resource` anymore so this property is depracated. I've left it with an empty setter per now to avoid errors, but it'll be removed in the future. + +~~You can set in this property wether the `getList` method will return an Array or not. Most of the times, it will return an array, as it returns a collection of values. However, sometimes this method returns first some metadata and inside it has the array. So this can be used together with `responseExtractor` to get the real array. The default value is true.~~ #### restangularFields @@ -281,7 +283,6 @@ Restangular required 3 fields for every "Restangularized" element. This are: * route: Name of the route of this element. Default: route * parentResource: The reference to the parent resource. Default: parentResource * restangularCollection: A boolean indicating if this is a collection or an element. Default: restangularCollection -* what: The name of the parameter to be used in inner $resource to handle the PATH of the url. For example, in `/users/123/messages`, `messages`represents the "what". Default: restangularWhat All of this fields except for `id` are handled by Restangular, so most of the time you won't change them. You can configure the name of the property that will be binded to all of this fields by setting restangularFields property. @@ -315,8 +316,6 @@ app.config(function(RestangularProvider) { RestangularProvider.setDefaultHttpFields({cache: true}); RestangularProvider.setMethodOverriders(["put", "patch"]); - RestangularProvider.setListTypeIsArray(true); - // In this case we configure that the id of each element will be the _id field and we change the Restangular route. We leave the default value for parentResource RestangularProvider.setRestangularFields({ id: "_id", @@ -519,14 +518,7 @@ Restangular.all("accounts").getList().then(function() { #### **I need to send one header in EVERY Restangular request, how do I do this?** -Restangular uses $http inside, so you can actually set default headers by using $httpProvider. This also applies to XSRF headers as well - -````javascript -app.config(["$httpProvider", function($httpProvider) { - $httpProvider.defaults.headers.common['Tenant-id'] = 'X'; - $httpProvider.defaults.headers.get['Gonto-id'] = 'P'; -}]); -```` +You can use `defaultHeaders` property for this or `$httpProvider.defaults.headers`, whichever suits you better. `defaultsHeaders` can be scoped with `withConfig` so it's really cool. #### Can I cache requests? @@ -573,8 +565,6 @@ In this case, you'd need to configure Restangular's `responseExtractor`and `list ````javascript app.config(function(RestangularProvider) { - // First let's set listTypeIsArray to false, as we have the array wrapped in some other object. - RestangularProvider.setListTypeIsArray(false); // Now let's configure the response extractor for each request RestangularProvider.setResponseExtractor(function(response, operation, what, url) { @@ -641,11 +631,7 @@ However, changes to that promise that you do from your HTML won't be seen in the #### When I set baseUrl with a port, it's stripped out. -Restangular uses `$resource` inside. `$resource` requires ports to be escaped to as not to think they are actually parameters. So the right way of setting a baseUrl with a port is the following: - -````javascript -RestangularProvider.setBaseUrl('http://localhost\\:8080'); -```` +It won't be stripped out anymore as I've ditched `$resource` :). Now you can happily put the port :). #### Why does this depend on Lodash / Underscore? @@ -658,10 +644,6 @@ So, why not use it? If you've never heard of them, by using Restangular, you cou Restangular supports both 1.0.X and 1.1.X up to versions 1.0.7 and 1.1.5. -When using Restangular with 1.1.X you get the following extra features: -* You can send custom headers using the `headers` parameter in all API calls -* You can use the `setHttpDefault` configuration method to set some $http defaults like `{cache: true}` - Also, when using Restangular with version >= 1.1.4, in case you're using Restangular inside a callback not handled by Angular, you've to wrap this all request with a `$scope.apply` to make it work or you need to run one extra `$digest` manually. Check out https://github.com/mgonto/restangular/issues/71 diff --git a/bower.json b/bower.json index fdc7e0a8..fc9461f6 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "0.8.4", + "version": "0.8.5", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { @@ -10,7 +10,6 @@ "dependencies": { "lodash": "~1.2.0", "angular": "*", - "angular-resource": "*" }, "ignore": [ "node_modules", diff --git a/package.json b/package.json index ac0fb440..29f7e93e 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "restangular", "description": "Restfull Resources service for AngularJS apps", - "version": "0.8.4", + "version": "0.8.5", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", "author": "Martin Gontovnikas ", diff --git a/src/restangular.js b/src/restangular.js index e43f2960..08a0e9fd 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -169,13 +169,10 @@ module.provider('Restangular', function() { } /** - * Sets the getList type. The getList returns an Array most of the time as it's a collection of values. - * However, sometimes you have metadata and in that cases, the getList ISN'T an array. - * By default, it's going to be set as array + * Depracated. Don't use this!! */ - config.listTypeIsArray = _.isUndefined(config.listTypeIsArray) ? true : config.listTypeIsArray; object.setListTypeIsArray = function(val) { - config.listTypeIsArray = val; + }; /** From c8dd43560f4e67425d0998739c60c9226cbc4571 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Thu, 20 Jun 2013 01:51:58 -0300 Subject: [PATCH 009/441] v0.8.6 --- CHANGELOG.md | 2 +- bower.json | 4 ++-- dist/restangular.js | 9 +++------ dist/restangular.min.js | 4 ++-- dist/restangular.zip | Bin 39998 -> 39541 bytes package.json | 2 +- 6 files changed, 9 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1491b92b..a1bd261a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -#0.8.5 +#0.8.6 * Ditched the buggy `$resource` and using `$http` inside :D #0.8.4 diff --git a/bower.json b/bower.json index fc9461f6..a44c52d7 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "0.8.5", + "version": "0.8.6", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { @@ -9,7 +9,7 @@ }, "dependencies": { "lodash": "~1.2.0", - "angular": "*", + "angular": "*" }, "ignore": [ "node_modules", diff --git a/dist/restangular.js b/dist/restangular.js index a1680f74..190d2aa1 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.4 - 2013-06-20 + * @version v0.8.6 - 2013-06-20 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT @@ -176,13 +176,10 @@ module.provider('Restangular', function() { } /** - * Sets the getList type. The getList returns an Array most of the time as it's a collection of values. - * However, sometimes you have metadata and in that cases, the getList ISN'T an array. - * By default, it's going to be set as array + * Depracated. Don't use this!! */ - config.listTypeIsArray = _.isUndefined(config.listTypeIsArray) ? true : config.listTypeIsArray; object.setListTypeIsArray = function(val) { - config.listTypeIsArray = val; + }; /** diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 70bbaf5e..17c9eae6 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.4 - 2013-06-20 + * @version v0.8.6 - 2013-06-20 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},b.listTypeIsArray=_.isUndefined(b.listTypeIsArray)?!0:b.listTypeIsArray,a.setListTypeIsArray=function(a){b.listTypeIsArray=a},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e,this.config.defaultRequestParams),h=_.defaults(d,this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];return c[b.config.restangularFields.restangularCollection]||(d+="/"+b.config.getIdFromElem(c)),d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(G.fetchUrl,G,b),b.addRestangularMethod=_.bind(D,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(C,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(C,a,b)})}),a.customGETLIST=_.bind(s,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(u,d),d.getList=_.bind(s,d),d.put=_.bind(w,d),d.post=_.bind(x,d),d.remove=_.bind(v,d),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,F)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(x,d,null),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.putElement=_.bind(r,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.getList=_.bind(s,d,null),n(d),f.transformElem(d,!0,c,F)}function r(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function s(a,b,e){var g=this,h=d.defer(),i="getList",k=G.fetchUrl(this,a),l=a||g[f.restangularFields.route];return f.requestInterceptor(null,i,l,k),G.resource(this,c,e,b,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?p(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):p(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?h.resolve(q(null,e,g[f.restangularFields.route])):h.resolve(q(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function t(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},n=g||this,o=b||this[f.restangularFields.route],q=G.fetchUrl(this,b),r=g||m(this);r=f.requestInterceptor(r,a,o,q);var s=function(c){var d=c.data,e=f.responseExtractor(d,a,o,q)||n;"post"!==a||i[f.restangularFields.restangularCollection]?k.resolve(p(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):k.resolve(p(i,e,b))},t=function(a){f.errorInterceptor(a),k.reject(a)},u=a,v=_.extend({},h),w=f.isOverridenMethod(a);return w&&(u="post",v=_.extend(v,{"X-HTTP-Method-Override":a})),f.isSafe(a)?w?G.resource(this,c,v,l,b)[u]({}).then(s,t):G.resource(this,c,v,l,b)[u]().then(s,t):G.resource(this,c,v,l,b)[u](r).then(s,t),j(k.promise)}function u(a,b){return _.bind(t,this)("get",void 0,a,void 0,b)}function v(a,b){return _.bind(t,this)("remove",void 0,a,void 0,b)}function w(a,b){return _.bind(t,this)("put",void 0,a,void 0,b)}function x(a,b,c,d){return _.bind(t,this)("post",a,c,b,d)}function y(a,b){return _.bind(t,this)("head",void 0,a,void 0,b)}function z(a,b){return _.bind(t,this)("trace",void 0,a,void 0,b)}function A(a,b){return _.bind(t,this)("options",void 0,a,void 0,b)}function B(a,b){return _.bind(t,this)("patch",void 0,a,void 0,b)}function C(a,b,c,d,e){return _.bind(t,this)(a,b,c,e,d)}function D(a,b,c,d,e,f){var g;g="getList"===b?_.bind(s,this,c):_.bind(C,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function E(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var F={},G=new f.urlCreatorFactory[f.urlCreator];return G.setConfig(f),F.copy=_.bind(o,F),F.withConfig=_.bind(E,F),F.one=_.bind(h,F,null),F.all=_.bind(i,F,null),F.restangularizeElement=_.bind(p,F),F.restangularizeCollection=_.bind(q,F),F}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e,this.config.defaultRequestParams),h=_.defaults(d,this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];return c[b.config.restangularFields.restangularCollection]||(d+="/"+b.config.getIdFromElem(c)),d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(G.fetchUrl,G,b),b.addRestangularMethod=_.bind(D,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(C,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(C,a,b)})}),a.customGETLIST=_.bind(s,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(u,d),d.getList=_.bind(s,d),d.put=_.bind(w,d),d.post=_.bind(x,d),d.remove=_.bind(v,d),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,F)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(x,d,null),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.putElement=_.bind(r,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.getList=_.bind(s,d,null),n(d),f.transformElem(d,!0,c,F)}function r(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function s(a,b,e){var g=this,h=d.defer(),i="getList",k=G.fetchUrl(this,a),l=a||g[f.restangularFields.route];return f.requestInterceptor(null,i,l,k),G.resource(this,c,e,b,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?p(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):p(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?h.resolve(q(null,e,g[f.restangularFields.route])):h.resolve(q(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function t(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},n=g||this,o=b||this[f.restangularFields.route],q=G.fetchUrl(this,b),r=g||m(this);r=f.requestInterceptor(r,a,o,q);var s=function(c){var d=c.data,e=f.responseExtractor(d,a,o,q)||n;"post"!==a||i[f.restangularFields.restangularCollection]?k.resolve(p(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):k.resolve(p(i,e,b))},t=function(a){f.errorInterceptor(a),k.reject(a)},u=a,v=_.extend({},h),w=f.isOverridenMethod(a);return w&&(u="post",v=_.extend(v,{"X-HTTP-Method-Override":a})),f.isSafe(a)?w?G.resource(this,c,v,l,b)[u]({}).then(s,t):G.resource(this,c,v,l,b)[u]().then(s,t):G.resource(this,c,v,l,b)[u](r).then(s,t),j(k.promise)}function u(a,b){return _.bind(t,this)("get",void 0,a,void 0,b)}function v(a,b){return _.bind(t,this)("remove",void 0,a,void 0,b)}function w(a,b){return _.bind(t,this)("put",void 0,a,void 0,b)}function x(a,b,c,d){return _.bind(t,this)("post",a,c,b,d)}function y(a,b){return _.bind(t,this)("head",void 0,a,void 0,b)}function z(a,b){return _.bind(t,this)("trace",void 0,a,void 0,b)}function A(a,b){return _.bind(t,this)("options",void 0,a,void 0,b)}function B(a,b){return _.bind(t,this)("patch",void 0,a,void 0,b)}function C(a,b,c,d,e){return _.bind(t,this)(a,b,c,e,d)}function D(a,b,c,d,e,f){var g;g="getList"===b?_.bind(s,this,c):_.bind(C,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function E(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var F={},G=new f.urlCreatorFactory[f.urlCreator];return G.setConfig(f),F.copy=_.bind(o,F),F.withConfig=_.bind(E,F),F.one=_.bind(h,F,null),F.all=_.bind(i,F,null),F.restangularizeElement=_.bind(p,F),F.restangularizeCollection=_.bind(q,F),F}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 67e7192db815b7a4379f1f42eff23a0cd861cc71..712ada3aae486231c177166fb3495117e42253ab 100644 GIT binary patch delta 221 zcmdnDgX!xQCY}IqW)?065UAms$fL+t!*|6g>&W#v8%r1%HkM4Zj%PHR{H|>4<^V=U zX&IN)f}+Ia#FEq$Jq4HiJoOTV(&AKwl8nq^Ma9X1va*wXS-B=Zku{pUA)a^gn&sw8!KR%19mr*U@Zljs>!x&CWsFJYY0a( delta 647 zcmZWnO>0v@6n%LuMnhgzENx1^Za}Ef5US0p606;`MUjU_a91XIH|faBoAPGnl~8ER zPbk+->)JnHDs)wF*B{`Y=&}?Mcg{ouHn}jfIQPsw=ia$LPu#OpH|xI~8_zg4eD5%u zzw3KH)*pTSUR_8W$DVrxdh+niW~xkG{jKMxQnU0dd#lq#^@>Xcs=bRPsO}&PkQkMY zBMB^m7jewm&=Q6x8lVhG@fHG;z}1prKwX3())g0#B_u4=C`%dmKOVxS*uwIIV2T;J0C;3Xn1VW!D2si;fvc^zua~OU6SJO1G}hY?V1wyU75{o` z3LZ5<38*1RRMvC<2fT$JcJcs4OFZVR!zTAgEvb< z1nS<*(Wkj5v^$=j9?C(*j^$~Fp4VpSU=n)ny!YO-zx2EO;o|(h", From 7d1ebf3ea9def40d989c6c6f656c7e6d2f14a4f8 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Thu, 20 Jun 2013 01:55:28 -0300 Subject: [PATCH 010/441] v0.8.7 Bugfix for refactor with $resource --- CHANGELOG.md | 3 +++ bower.json | 2 +- dist/restangular.js | 6 +++--- dist/restangular.min.js | 4 ++-- dist/restangular.zip | Bin 39541 -> 39561 bytes package.json | 2 +- src/restangular.js | 4 ++-- 7 files changed, 12 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a1bd261a..cc2a3a87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +#0.8.7 +* Bugfix for Refactor + #0.8.6 * Ditched the buggy `$resource` and using `$http` inside :D diff --git a/bower.json b/bower.json index a44c52d7..e33a16e8 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "0.8.6", + "version": "0.8.7", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { diff --git a/dist/restangular.js b/dist/restangular.js index 190d2aa1..68895537 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.6 - 2013-06-20 + * @version v0.8.7 - 2013-06-20 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT @@ -295,8 +295,8 @@ module.provider('Restangular', function() { BaseCreator.prototype.resource = function(current, $http, callHeaders, callParams, what) { - var params = _.defaults(callParams, this.config.defaultRequestParams); - var headers = _.defaults(callHeaders, this.config.defaultHeaders); + var params = _.defaults(callParams || {}, this.config.defaultRequestParams); + var headers = _.defaults(callHeaders || {}, this.config.defaultHeaders); var url = this.base(current); url += what ? ("/" + what): ''; diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 17c9eae6..b449e9d1 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.6 - 2013-06-20 + * @version v0.8.7 - 2013-06-20 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e,this.config.defaultRequestParams),h=_.defaults(d,this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];return c[b.config.restangularFields.restangularCollection]||(d+="/"+b.config.getIdFromElem(c)),d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(G.fetchUrl,G,b),b.addRestangularMethod=_.bind(D,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(C,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(C,a,b)})}),a.customGETLIST=_.bind(s,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(u,d),d.getList=_.bind(s,d),d.put=_.bind(w,d),d.post=_.bind(x,d),d.remove=_.bind(v,d),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,F)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(x,d,null),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.putElement=_.bind(r,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.getList=_.bind(s,d,null),n(d),f.transformElem(d,!0,c,F)}function r(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function s(a,b,e){var g=this,h=d.defer(),i="getList",k=G.fetchUrl(this,a),l=a||g[f.restangularFields.route];return f.requestInterceptor(null,i,l,k),G.resource(this,c,e,b,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?p(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):p(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?h.resolve(q(null,e,g[f.restangularFields.route])):h.resolve(q(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function t(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},n=g||this,o=b||this[f.restangularFields.route],q=G.fetchUrl(this,b),r=g||m(this);r=f.requestInterceptor(r,a,o,q);var s=function(c){var d=c.data,e=f.responseExtractor(d,a,o,q)||n;"post"!==a||i[f.restangularFields.restangularCollection]?k.resolve(p(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):k.resolve(p(i,e,b))},t=function(a){f.errorInterceptor(a),k.reject(a)},u=a,v=_.extend({},h),w=f.isOverridenMethod(a);return w&&(u="post",v=_.extend(v,{"X-HTTP-Method-Override":a})),f.isSafe(a)?w?G.resource(this,c,v,l,b)[u]({}).then(s,t):G.resource(this,c,v,l,b)[u]().then(s,t):G.resource(this,c,v,l,b)[u](r).then(s,t),j(k.promise)}function u(a,b){return _.bind(t,this)("get",void 0,a,void 0,b)}function v(a,b){return _.bind(t,this)("remove",void 0,a,void 0,b)}function w(a,b){return _.bind(t,this)("put",void 0,a,void 0,b)}function x(a,b,c,d){return _.bind(t,this)("post",a,c,b,d)}function y(a,b){return _.bind(t,this)("head",void 0,a,void 0,b)}function z(a,b){return _.bind(t,this)("trace",void 0,a,void 0,b)}function A(a,b){return _.bind(t,this)("options",void 0,a,void 0,b)}function B(a,b){return _.bind(t,this)("patch",void 0,a,void 0,b)}function C(a,b,c,d,e){return _.bind(t,this)(a,b,c,e,d)}function D(a,b,c,d,e,f){var g;g="getList"===b?_.bind(s,this,c):_.bind(C,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function E(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var F={},G=new f.urlCreatorFactory[f.urlCreator];return G.setConfig(f),F.copy=_.bind(o,F),F.withConfig=_.bind(E,F),F.one=_.bind(h,F,null),F.all=_.bind(i,F,null),F.restangularizeElement=_.bind(p,F),F.restangularizeCollection=_.bind(q,F),F}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];return c[b.config.restangularFields.restangularCollection]||(d+="/"+b.config.getIdFromElem(c)),d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(G.fetchUrl,G,b),b.addRestangularMethod=_.bind(D,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(C,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(C,a,b)})}),a.customGETLIST=_.bind(s,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(u,d),d.getList=_.bind(s,d),d.put=_.bind(w,d),d.post=_.bind(x,d),d.remove=_.bind(v,d),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,F)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(x,d,null),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.putElement=_.bind(r,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.getList=_.bind(s,d,null),n(d),f.transformElem(d,!0,c,F)}function r(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function s(a,b,e){var g=this,h=d.defer(),i="getList",k=G.fetchUrl(this,a),l=a||g[f.restangularFields.route];return f.requestInterceptor(null,i,l,k),G.resource(this,c,e,b,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?p(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):p(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?h.resolve(q(null,e,g[f.restangularFields.route])):h.resolve(q(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function t(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},n=g||this,o=b||this[f.restangularFields.route],q=G.fetchUrl(this,b),r=g||m(this);r=f.requestInterceptor(r,a,o,q);var s=function(c){var d=c.data,e=f.responseExtractor(d,a,o,q)||n;"post"!==a||i[f.restangularFields.restangularCollection]?k.resolve(p(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):k.resolve(p(i,e,b))},t=function(a){f.errorInterceptor(a),k.reject(a)},u=a,v=_.extend({},h),w=f.isOverridenMethod(a);return w&&(u="post",v=_.extend(v,{"X-HTTP-Method-Override":a})),f.isSafe(a)?w?G.resource(this,c,v,l,b)[u]({}).then(s,t):G.resource(this,c,v,l,b)[u]().then(s,t):G.resource(this,c,v,l,b)[u](r).then(s,t),j(k.promise)}function u(a,b){return _.bind(t,this)("get",void 0,a,void 0,b)}function v(a,b){return _.bind(t,this)("remove",void 0,a,void 0,b)}function w(a,b){return _.bind(t,this)("put",void 0,a,void 0,b)}function x(a,b,c,d){return _.bind(t,this)("post",a,c,b,d)}function y(a,b){return _.bind(t,this)("head",void 0,a,void 0,b)}function z(a,b){return _.bind(t,this)("trace",void 0,a,void 0,b)}function A(a,b){return _.bind(t,this)("options",void 0,a,void 0,b)}function B(a,b){return _.bind(t,this)("patch",void 0,a,void 0,b)}function C(a,b,c,d,e){return _.bind(t,this)(a,b,c,e,d)}function D(a,b,c,d,e,f){var g;g="getList"===b?_.bind(s,this,c):_.bind(C,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function E(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var F={},G=new f.urlCreatorFactory[f.urlCreator];return G.setConfig(f),F.copy=_.bind(o,F),F.withConfig=_.bind(E,F),F.one=_.bind(h,F,null),F.all=_.bind(i,F,null),F.restangularizeElement=_.bind(p,F),F.restangularizeCollection=_.bind(q,F),F}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 712ada3aae486231c177166fb3495117e42253ab..a386a64232732d2e8dc5d183344aa78408ed2010 100644 GIT binary patch delta 222 zcmeymg{gBZ6L)|&GYc032)v!htt9xC?~2pb_568zOBfhHSa`BRsmR124@UFJjip;R z2QYrs=2fVvQK+ufQ7FmCEY_P`$1XiNUDuoqBD#5=ZlOCb$Q0j)RnjFY3=AccWlB>R z%{MoePUhvRsR3$4=re5=U", diff --git a/src/restangular.js b/src/restangular.js index 08a0e9fd..8604f456 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -288,8 +288,8 @@ module.provider('Restangular', function() { BaseCreator.prototype.resource = function(current, $http, callHeaders, callParams, what) { - var params = _.defaults(callParams, this.config.defaultRequestParams); - var headers = _.defaults(callHeaders, this.config.defaultHeaders); + var params = _.defaults(callParams || {}, this.config.defaultRequestParams); + var headers = _.defaults(callHeaders || {}, this.config.defaultHeaders); var url = this.base(current); url += what ? ("/" + what): ''; From 93ea485b47fb1b077d523b0cedf75a6696c27280 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Thu, 20 Jun 2013 03:08:54 -0300 Subject: [PATCH 011/441] Travis tests fixed. Using firefox instead of PhantomJS --- .travis.yml | 4 ++++ Gruntfile.js | 13 +++++++++++++ package.json | 2 +- 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 6e5919de..ecde5ad6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,7 @@ language: node_js node_js: - "0.10" + + before_script: + - export DISPLAY=:99.0 + - sh -e /etc/init.d/xvfb start diff --git a/Gruntfile.js b/Gruntfile.js index 04020773..e6a5bc56 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -78,6 +78,17 @@ module.exports = function(grunt) { singleRun: true, autoWatch: false }, + travis: { + singleRun: true, + autoWatch: false, + browsers: ['Firefox'] + }, + travisUnderscore: { + singleRun: true, + autoWatch: false, + browsers: ['Firefox'], + configFile: 'karma.underscore.conf.js', + }, buildUnderscore: { configFile: 'karma.underscore.conf.js', singleRun: true, @@ -123,6 +134,8 @@ module.exports = function(grunt) { grunt.registerTask('build', ['bowerInstall', 'bower', 'karma:build', 'karma:buildUnderscore', 'concat', 'uglify', 'zip']); grunt.registerTask('test', ['karma:build', 'karma:buildUnderscore']); + + grunt.registerTask('travis', ['karma:travis', 'karma:travisUnderscore']); // Provides the "bump" task. grunt.registerTask('bump', 'Increment version number', function() { diff --git a/package.json b/package.json index 5056fd06..dd8f3116 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,6 @@ "grunt-zip": "*" }, "scripts": { - "test": "grunt test --verbose" + "test": "grunt travis --verbose" } } \ No newline at end of file From 582199ec7599da21dfae0c7c6015a3159f914a71 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Thu, 20 Jun 2013 03:10:07 -0300 Subject: [PATCH 012/441] Fixed .travis.yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ecde5ad6..1426a7a2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,6 +2,6 @@ language: node_js node_js: - "0.10" - before_script: +before_script: - export DISPLAY=:99.0 - sh -e /etc/init.d/xvfb start From 3164dea99778165162f1c6c6026771c3c5d9b0e1 Mon Sep 17 00:00:00 2001 From: Chris Boden Date: Thu, 20 Jun 2013 11:45:33 -0400 Subject: [PATCH 013/441] Do not add trailing slash Ensures a "/" is not added to a request --- dist/restangular.js | 7 +++++-- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 39561 -> 39669 bytes src/restangular.js | 7 +++++-- 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/dist/restangular.js b/dist/restangular.js index 68895537..87055f1d 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -357,9 +357,12 @@ module.provider('Restangular', function() { var currUrl = acum + "/" + elem[__this.config.restangularFields.route]; if (!elem[__this.config.restangularFields.restangularCollection]) { - currUrl += "/" + __this.config.getIdFromElem(elem); + var elemId = __this.config.getIdFromElem(elem); + if (elemId) { + currUrl += "/" + elemId; + } } - + return currUrl; }, ''); } diff --git a/dist/restangular.min.js b/dist/restangular.min.js index b449e9d1..cbfe4a87 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -5,4 +5,4 @@ * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];return c[b.config.restangularFields.restangularCollection]||(d+="/"+b.config.getIdFromElem(c)),d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(G.fetchUrl,G,b),b.addRestangularMethod=_.bind(D,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(C,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(C,a,b)})}),a.customGETLIST=_.bind(s,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(u,d),d.getList=_.bind(s,d),d.put=_.bind(w,d),d.post=_.bind(x,d),d.remove=_.bind(v,d),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,F)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(x,d,null),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.putElement=_.bind(r,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.getList=_.bind(s,d,null),n(d),f.transformElem(d,!0,c,F)}function r(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function s(a,b,e){var g=this,h=d.defer(),i="getList",k=G.fetchUrl(this,a),l=a||g[f.restangularFields.route];return f.requestInterceptor(null,i,l,k),G.resource(this,c,e,b,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?p(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):p(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?h.resolve(q(null,e,g[f.restangularFields.route])):h.resolve(q(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function t(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},n=g||this,o=b||this[f.restangularFields.route],q=G.fetchUrl(this,b),r=g||m(this);r=f.requestInterceptor(r,a,o,q);var s=function(c){var d=c.data,e=f.responseExtractor(d,a,o,q)||n;"post"!==a||i[f.restangularFields.restangularCollection]?k.resolve(p(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):k.resolve(p(i,e,b))},t=function(a){f.errorInterceptor(a),k.reject(a)},u=a,v=_.extend({},h),w=f.isOverridenMethod(a);return w&&(u="post",v=_.extend(v,{"X-HTTP-Method-Override":a})),f.isSafe(a)?w?G.resource(this,c,v,l,b)[u]({}).then(s,t):G.resource(this,c,v,l,b)[u]().then(s,t):G.resource(this,c,v,l,b)[u](r).then(s,t),j(k.promise)}function u(a,b){return _.bind(t,this)("get",void 0,a,void 0,b)}function v(a,b){return _.bind(t,this)("remove",void 0,a,void 0,b)}function w(a,b){return _.bind(t,this)("put",void 0,a,void 0,b)}function x(a,b,c,d){return _.bind(t,this)("post",a,c,b,d)}function y(a,b){return _.bind(t,this)("head",void 0,a,void 0,b)}function z(a,b){return _.bind(t,this)("trace",void 0,a,void 0,b)}function A(a,b){return _.bind(t,this)("options",void 0,a,void 0,b)}function B(a,b){return _.bind(t,this)("patch",void 0,a,void 0,b)}function C(a,b,c,d,e){return _.bind(t,this)(a,b,c,e,d)}function D(a,b,c,d,e,f){var g;g="getList"===b?_.bind(s,this,c):_.bind(C,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function E(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var F={},G=new f.urlCreatorFactory[f.urlCreator];return G.setConfig(f),F.copy=_.bind(o,F),F.withConfig=_.bind(E,F),F.one=_.bind(h,F,null),F.all=_.bind(i,F,null),F.restangularizeElement=_.bind(p,F),F.restangularizeCollection=_.bind(q,F),F}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(G.fetchUrl,G,b),b.addRestangularMethod=_.bind(D,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(C,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(C,a,b)})}),a.customGETLIST=_.bind(s,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(u,d),d.getList=_.bind(s,d),d.put=_.bind(w,d),d.post=_.bind(x,d),d.remove=_.bind(v,d),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,F)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(x,d,null),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.putElement=_.bind(r,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.getList=_.bind(s,d,null),n(d),f.transformElem(d,!0,c,F)}function r(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function s(a,b,e){var g=this,h=d.defer(),i="getList",k=G.fetchUrl(this,a),l=a||g[f.restangularFields.route];return f.requestInterceptor(null,i,l,k),G.resource(this,c,e,b,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?p(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):p(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?h.resolve(q(null,e,g[f.restangularFields.route])):h.resolve(q(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function t(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},n=g||this,o=b||this[f.restangularFields.route],q=G.fetchUrl(this,b),r=g||m(this);r=f.requestInterceptor(r,a,o,q);var s=function(c){var d=c.data,e=f.responseExtractor(d,a,o,q)||n;"post"!==a||i[f.restangularFields.restangularCollection]?k.resolve(p(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):k.resolve(p(i,e,b))},t=function(a){f.errorInterceptor(a),k.reject(a)},u=a,v=_.extend({},h),w=f.isOverridenMethod(a);return w&&(u="post",v=_.extend(v,{"X-HTTP-Method-Override":a})),f.isSafe(a)?w?G.resource(this,c,v,l,b)[u]({}).then(s,t):G.resource(this,c,v,l,b)[u]().then(s,t):G.resource(this,c,v,l,b)[u](r).then(s,t),j(k.promise)}function u(a,b){return _.bind(t,this)("get",void 0,a,void 0,b)}function v(a,b){return _.bind(t,this)("remove",void 0,a,void 0,b)}function w(a,b){return _.bind(t,this)("put",void 0,a,void 0,b)}function x(a,b,c,d){return _.bind(t,this)("post",a,c,b,d)}function y(a,b){return _.bind(t,this)("head",void 0,a,void 0,b)}function z(a,b){return _.bind(t,this)("trace",void 0,a,void 0,b)}function A(a,b){return _.bind(t,this)("options",void 0,a,void 0,b)}function B(a,b){return _.bind(t,this)("patch",void 0,a,void 0,b)}function C(a,b,c,d,e){return _.bind(t,this)(a,b,c,e,d)}function D(a,b,c,d,e,f){var g;g="getList"===b?_.bind(s,this,c):_.bind(C,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function E(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var F={},G=new f.urlCreatorFactory[f.urlCreator];return G.setConfig(f),F.copy=_.bind(o,F),F.withConfig=_.bind(E,F),F.one=_.bind(h,F,null),F.all=_.bind(i,F,null),F.restangularizeElement=_.bind(p,F),F.restangularizeCollection=_.bind(q,F),F}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index a386a64232732d2e8dc5d183344aa78408ed2010..4ddd91acf0c71042c32577356ebd520b89039a28 100644 GIT binary patch delta 274 zcmeC&%Jg+B6HkCQGYc032xQhyMR_oIjOmx zDGIiex0_o`UZBXrm6@iX0TG<67%nyWgBIK5<>rEHP@#{}5|ica#3oDe2u?n4$T3-< zh-0&o#ZMbvkn!Fs4bsgj3=GYSHA;n8GSf5^C+oKxb81$XB^D{9+9pljXD%j@tZAL9 zrlygiZL6fOq@Ai+Ta;Q-T9l`-xxL+9h$*vn@`;&-XpWuCKFe4E#R8xu;$XkQh`iFt Xx}}n00p6@^AR%TT+zF)BW`TGBzi& Date: Thu, 20 Jun 2013 12:55:56 -0300 Subject: [PATCH 014/441] 0.8.8 --- CHANGELOG.md | 3 +++ bower.json | 2 +- dist/restangular.js | 2 +- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 39669 -> 39669 bytes package.json | 2 +- 6 files changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc2a3a87..0d44814f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +#0.8.8 +* Removed extra trailling slash for elements without ID. Thanks @cboden + #0.8.7 * Bugfix for Refactor diff --git a/bower.json b/bower.json index e33a16e8..61eb1ac9 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "0.8.7", + "version": "0.8.8", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { diff --git a/dist/restangular.js b/dist/restangular.js index 87055f1d..a8e80f2a 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.7 - 2013-06-20 + * @version v0.8.8 - 2013-06-20 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.min.js b/dist/restangular.min.js index cbfe4a87..dd30b138 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.7 - 2013-06-20 + * @version v0.8.8 - 2013-06-20 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.zip b/dist/restangular.zip index 4ddd91acf0c71042c32577356ebd520b89039a28..678544868658c5f3eb1cfbb53775a0b9f3d95707 100644 GIT binary patch delta 96 zcmeymmFeqNCY}IqW)?065crukkw=l^XWA7f-&27vCz_@*T5Ozsw*)Nmsq@K<$ql8M ij207TZ{0k*o1ola-k=YbTq`GK8z2oIA@Bp>*9WcL0FBB&GlW diff --git a/package.json b/package.json index dd8f3116..dda9c837 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "restangular", "description": "Restfull Resources service for AngularJS apps", - "version": "0.8.7", + "version": "0.8.8", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", "author": "Martin Gontovnikas ", From 1a9e8ea07c3c1205a4f0eada4ba9edc5f2b954da Mon Sep 17 00:00:00 2001 From: Calvin Lai Date: Thu, 20 Jun 2013 16:34:55 -0400 Subject: [PATCH 015/441] version bump --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d44814f..62dfbc27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +#0.8.9 +* Fix call to `isOverridenMethod` in `setMethodOverriders`. + #0.8.8 * Removed extra trailling slash for elements without ID. Thanks @cboden From 019d746dae19a13c5c971e927bf7e02cc95a1aca Mon Sep 17 00:00:00 2001 From: Calvin Lai Date: Thu, 20 Jun 2013 16:35:52 -0400 Subject: [PATCH 016/441] fix call to isOverridenMethod in setMethodOverriders --- src/restangular.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/restangular.js b/src/restangular.js index 3407eb37..f2e0ac30 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -57,7 +57,7 @@ module.provider('Restangular', function() { config.methodOverriders = config.methodOverriders || []; object.setMethodOverriders = function(values) { var overriders = _.extend([], values); - if (isOverridenMethod('delete', overriders)) { + if (config.isOverridenMethod('delete', overriders)) { overriders.push("remove"); } config.methodOverriders = overriders; @@ -702,4 +702,4 @@ module.provider('Restangular', function() { } ); -})(); \ No newline at end of file +})(); From 58e5da2e59b110b5d3d1c07d9d426441ae482244 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Thu, 20 Jun 2013 17:45:27 -0300 Subject: [PATCH 017/441] v0.8.9 --- bower.json | 2 +- dist/restangular.js | 6 +++--- dist/restangular.min.js | 4 ++-- dist/restangular.zip | Bin 39669 -> 39679 bytes package.json | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/bower.json b/bower.json index 61eb1ac9..35e7ebaf 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "0.8.8", + "version": "0.8.9", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { diff --git a/dist/restangular.js b/dist/restangular.js index a8e80f2a..60e6f66b 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.8 - 2013-06-20 + * @version v0.8.9 - 2013-06-20 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT @@ -64,7 +64,7 @@ module.provider('Restangular', function() { config.methodOverriders = config.methodOverriders || []; object.setMethodOverriders = function(values) { var overriders = _.extend([], values); - if (isOverridenMethod('delete', overriders)) { + if (config.isOverridenMethod('delete', overriders)) { overriders.push("remove"); } config.methodOverriders = overriders; @@ -709,4 +709,4 @@ module.provider('Restangular', function() { } ); -})(); \ No newline at end of file +})(); diff --git a/dist/restangular.min.js b/dist/restangular.min.js index dd30b138..67180059 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.8 - 2013-06-20 + * @version v0.8.9 - 2013-06-20 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(G.fetchUrl,G,b),b.addRestangularMethod=_.bind(D,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(C,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(C,a,b)})}),a.customGETLIST=_.bind(s,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(u,d),d.getList=_.bind(s,d),d.put=_.bind(w,d),d.post=_.bind(x,d),d.remove=_.bind(v,d),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,F)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(x,d,null),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.putElement=_.bind(r,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.getList=_.bind(s,d,null),n(d),f.transformElem(d,!0,c,F)}function r(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function s(a,b,e){var g=this,h=d.defer(),i="getList",k=G.fetchUrl(this,a),l=a||g[f.restangularFields.route];return f.requestInterceptor(null,i,l,k),G.resource(this,c,e,b,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?p(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):p(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?h.resolve(q(null,e,g[f.restangularFields.route])):h.resolve(q(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function t(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},n=g||this,o=b||this[f.restangularFields.route],q=G.fetchUrl(this,b),r=g||m(this);r=f.requestInterceptor(r,a,o,q);var s=function(c){var d=c.data,e=f.responseExtractor(d,a,o,q)||n;"post"!==a||i[f.restangularFields.restangularCollection]?k.resolve(p(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):k.resolve(p(i,e,b))},t=function(a){f.errorInterceptor(a),k.reject(a)},u=a,v=_.extend({},h),w=f.isOverridenMethod(a);return w&&(u="post",v=_.extend(v,{"X-HTTP-Method-Override":a})),f.isSafe(a)?w?G.resource(this,c,v,l,b)[u]({}).then(s,t):G.resource(this,c,v,l,b)[u]().then(s,t):G.resource(this,c,v,l,b)[u](r).then(s,t),j(k.promise)}function u(a,b){return _.bind(t,this)("get",void 0,a,void 0,b)}function v(a,b){return _.bind(t,this)("remove",void 0,a,void 0,b)}function w(a,b){return _.bind(t,this)("put",void 0,a,void 0,b)}function x(a,b,c,d){return _.bind(t,this)("post",a,c,b,d)}function y(a,b){return _.bind(t,this)("head",void 0,a,void 0,b)}function z(a,b){return _.bind(t,this)("trace",void 0,a,void 0,b)}function A(a,b){return _.bind(t,this)("options",void 0,a,void 0,b)}function B(a,b){return _.bind(t,this)("patch",void 0,a,void 0,b)}function C(a,b,c,d,e){return _.bind(t,this)(a,b,c,e,d)}function D(a,b,c,d,e,f){var g;g="getList"===b?_.bind(s,this,c):_.bind(C,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function E(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var F={},G=new f.urlCreatorFactory[f.urlCreator];return G.setConfig(f),F.copy=_.bind(o,F),F.withConfig=_.bind(E,F),F.one=_.bind(h,F,null),F.all=_.bind(i,F,null),F.restangularizeElement=_.bind(p,F),F.restangularizeCollection=_.bind(q,F),F}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(G.fetchUrl,G,b),b.addRestangularMethod=_.bind(D,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(C,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(C,a,b)})}),a.customGETLIST=_.bind(s,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(u,d),d.getList=_.bind(s,d),d.put=_.bind(w,d),d.post=_.bind(x,d),d.remove=_.bind(v,d),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,F)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(x,d,null),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.putElement=_.bind(r,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.getList=_.bind(s,d,null),n(d),f.transformElem(d,!0,c,F)}function r(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function s(a,b,e){var g=this,h=d.defer(),i="getList",k=G.fetchUrl(this,a),l=a||g[f.restangularFields.route];return f.requestInterceptor(null,i,l,k),G.resource(this,c,e,b,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?p(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):p(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?h.resolve(q(null,e,g[f.restangularFields.route])):h.resolve(q(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function t(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},n=g||this,o=b||this[f.restangularFields.route],q=G.fetchUrl(this,b),r=g||m(this);r=f.requestInterceptor(r,a,o,q);var s=function(c){var d=c.data,e=f.responseExtractor(d,a,o,q)||n;"post"!==a||i[f.restangularFields.restangularCollection]?k.resolve(p(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):k.resolve(p(i,e,b))},t=function(a){f.errorInterceptor(a),k.reject(a)},u=a,v=_.extend({},h),w=f.isOverridenMethod(a);return w&&(u="post",v=_.extend(v,{"X-HTTP-Method-Override":a})),f.isSafe(a)?w?G.resource(this,c,v,l,b)[u]({}).then(s,t):G.resource(this,c,v,l,b)[u]().then(s,t):G.resource(this,c,v,l,b)[u](r).then(s,t),j(k.promise)}function u(a,b){return _.bind(t,this)("get",void 0,a,void 0,b)}function v(a,b){return _.bind(t,this)("remove",void 0,a,void 0,b)}function w(a,b){return _.bind(t,this)("put",void 0,a,void 0,b)}function x(a,b,c,d){return _.bind(t,this)("post",a,c,b,d)}function y(a,b){return _.bind(t,this)("head",void 0,a,void 0,b)}function z(a,b){return _.bind(t,this)("trace",void 0,a,void 0,b)}function A(a,b){return _.bind(t,this)("options",void 0,a,void 0,b)}function B(a,b){return _.bind(t,this)("patch",void 0,a,void 0,b)}function C(a,b,c,d,e){return _.bind(t,this)(a,b,c,e,d)}function D(a,b,c,d,e,f){var g;g="getList"===b?_.bind(s,this,c):_.bind(C,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function E(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var F={},G=new f.urlCreatorFactory[f.urlCreator];return G.setConfig(f),F.copy=_.bind(o,F),F.withConfig=_.bind(E,F),F.one=_.bind(h,F,null),F.all=_.bind(i,F,null),F.restangularizeElement=_.bind(p,F),F.restangularizeCollection=_.bind(q,F),F}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 678544868658c5f3eb1cfbb53775a0b9f3d95707..65e3425e3f537426713086380da05c3b4374980c 100644 GIT binary patch delta 169 zcmeymmFfRhCY}IqW)?065Ln$ikw=ktb?+6YnXj$Plu8*GlqOmwFj{V$y_s|J15M7& z0bFv~5?sg{t~mW={q(0*g@K`Ua%*V{qvgceTQ|=yvtwaO(%XEuDpa0nb?;=8S%#>l fPA-~dA`h|$t{G^6IM@v^qHOZfSz2rcvp{?R#pE^c delta 173 zcmeyrmFeqNCY}IqW)?065crukkw;PRXWA7f-&27vrAiqXKv;P4#8Q!oK^}}28)t9k zoO~gLYjZr8ShhH_zAH|jI-ksFR$*Xhp4?lS!e}vZ_SVhI%j{S-Kd%avXZo2o*>090 iFN(>NYi60qgGAsufx5-P?tl?_lh4o6VpE$1;sXF+MmcQ& diff --git a/package.json b/package.json index dda9c837..a5760875 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "restangular", "description": "Restfull Resources service for AngularJS apps", - "version": "0.8.8", + "version": "0.8.9", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", "author": "Martin Gontovnikas ", From 334d4136c48b6c9dba4c2a15730b4641c40aaa9b Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Thu, 20 Jun 2013 18:04:59 -0300 Subject: [PATCH 018/441] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 49b14143..0c58e4dc 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ Restangular has several features that distinguish it from $resource: * **It uses promises**. Instead of doing the "magic" filling of objects like $resource, it uses promises. * **You can use this in $routeProvider.resolve**. As Restangular returns promises, you can return any of the methods in the `$routeProvider.resolve` and you'll get the real object injected into your controller if you want. +* **It doesn't have all those `$resource` bugs**. Restangular doesn't have problem with trailling slashes, additional `:` in the URL, escapaing information, expecting only arrays for getting lists, etc. * **It supports all HTTP methods**. * **You don't have to create one $resource object per request**. Each time you want to do a request, you can just do it using the object that was returned by Restangular. You don't need to create a new object for this. * **You don't have to write or remember ANY URL**. With $resource, you need to write the URL Template. In here, you don't write any urls. You just write the name of the resource you want to fetch and that's it. From d3859101bb27ad504d809104cd233ebe0924e535 Mon Sep 17 00:00:00 2001 From: Zenobius Jiricek Date: Mon, 24 Jun 2013 06:08:29 +0930 Subject: [PATCH 019/441] Update README.md Indicate that restangular works well with django-tastypie --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 0c58e4dc..5b5a8745 100644 --- a/README.md +++ b/README.md @@ -656,6 +656,7 @@ This server frameworks play real nice with Restangular, as they let you create a * CakePHP for PHP * Play1 & 2 for Java & scala * Restify and Express for NodeJS +* Tastypie for Django # Releases Notes From 70b1e714d8f557c92f773d37d15e1dc0288b66df Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Tue, 25 Jun 2013 17:10:32 -0300 Subject: [PATCH 020/441] Added one and all to all elements. Now you can build any URL with Restangular Fixes #138 --- dist/restangular.js | 10 +++++----- dist/restangular.min.js | 4 ++-- dist/restangular.zip | Bin 39679 -> 39650 bytes src/restangular.js | 8 ++++---- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/dist/restangular.js b/dist/restangular.js index 60e6f66b..2f366221 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.9 - 2013-06-20 + * @version v0.8.9 - 2013-06-25 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT @@ -403,6 +403,10 @@ module.provider('Restangular', function() { elem.getRestangularUrl = _.bind(urlHandler.fetchUrl, urlHandler, elem); elem.addRestangularMethod = _.bind(addRestangularMethodFunction, elem); + // RequestLess connection + elem.one = _.bind(one, elem, elem); + elem.all = _.bind(all, elem, elem); + if (parent) { var restangularFieldsForParent = _.union( _.values( _.pick(config.restangularFields, ['id', 'route', 'parentResource']) ), @@ -494,10 +498,6 @@ module.provider('Restangular', function() { localElem.options = _.bind(optionsFunction, localElem); localElem.patch = _.bind(patchFunction, localElem); - //RequestLess connection - localElem.one = _.bind(one, localElem, localElem); - localElem.all = _.bind(all, localElem, localElem); - addCustomOperation(localElem); return config.transformElem(localElem, false, route, service); } diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 67180059..a6196fdc 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.9 - 2013-06-20 + * @version v0.8.9 - 2013-06-25 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(G.fetchUrl,G,b),b.addRestangularMethod=_.bind(D,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(C,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(C,a,b)})}),a.customGETLIST=_.bind(s,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(u,d),d.getList=_.bind(s,d),d.put=_.bind(w,d),d.post=_.bind(x,d),d.remove=_.bind(v,d),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.one=_.bind(h,d,d),d.all=_.bind(i,d,d),n(d),f.transformElem(d,!1,c,F)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(x,d,null),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.putElement=_.bind(r,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.getList=_.bind(s,d,null),n(d),f.transformElem(d,!0,c,F)}function r(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function s(a,b,e){var g=this,h=d.defer(),i="getList",k=G.fetchUrl(this,a),l=a||g[f.restangularFields.route];return f.requestInterceptor(null,i,l,k),G.resource(this,c,e,b,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?p(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):p(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?h.resolve(q(null,e,g[f.restangularFields.route])):h.resolve(q(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function t(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},n=g||this,o=b||this[f.restangularFields.route],q=G.fetchUrl(this,b),r=g||m(this);r=f.requestInterceptor(r,a,o,q);var s=function(c){var d=c.data,e=f.responseExtractor(d,a,o,q)||n;"post"!==a||i[f.restangularFields.restangularCollection]?k.resolve(p(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):k.resolve(p(i,e,b))},t=function(a){f.errorInterceptor(a),k.reject(a)},u=a,v=_.extend({},h),w=f.isOverridenMethod(a);return w&&(u="post",v=_.extend(v,{"X-HTTP-Method-Override":a})),f.isSafe(a)?w?G.resource(this,c,v,l,b)[u]({}).then(s,t):G.resource(this,c,v,l,b)[u]().then(s,t):G.resource(this,c,v,l,b)[u](r).then(s,t),j(k.promise)}function u(a,b){return _.bind(t,this)("get",void 0,a,void 0,b)}function v(a,b){return _.bind(t,this)("remove",void 0,a,void 0,b)}function w(a,b){return _.bind(t,this)("put",void 0,a,void 0,b)}function x(a,b,c,d){return _.bind(t,this)("post",a,c,b,d)}function y(a,b){return _.bind(t,this)("head",void 0,a,void 0,b)}function z(a,b){return _.bind(t,this)("trace",void 0,a,void 0,b)}function A(a,b){return _.bind(t,this)("options",void 0,a,void 0,b)}function B(a,b){return _.bind(t,this)("patch",void 0,a,void 0,b)}function C(a,b,c,d,e){return _.bind(t,this)(a,b,c,e,d)}function D(a,b,c,d,e,f){var g;g="getList"===b?_.bind(s,this,c):_.bind(C,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function E(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var F={},G=new f.urlCreatorFactory[f.urlCreator];return G.setConfig(f),F.copy=_.bind(o,F),F.withConfig=_.bind(E,F),F.one=_.bind(h,F,null),F.all=_.bind(i,F,null),F.restangularizeElement=_.bind(p,F),F.restangularizeCollection=_.bind(q,F),F}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(G.fetchUrl,G,b),b.addRestangularMethod=_.bind(D,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(C,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(C,a,b)})}),a.customGETLIST=_.bind(s,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(u,d),d.getList=_.bind(s,d),d.put=_.bind(w,d),d.post=_.bind(x,d),d.remove=_.bind(v,d),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),n(d),f.transformElem(d,!1,c,F)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(x,d,null),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.putElement=_.bind(r,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.getList=_.bind(s,d,null),n(d),f.transformElem(d,!0,c,F)}function r(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function s(a,b,e){var g=this,h=d.defer(),i="getList",k=G.fetchUrl(this,a),l=a||g[f.restangularFields.route];return f.requestInterceptor(null,i,l,k),G.resource(this,c,e,b,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?p(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):p(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?h.resolve(q(null,e,g[f.restangularFields.route])):h.resolve(q(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function t(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},n=g||this,o=b||this[f.restangularFields.route],q=G.fetchUrl(this,b),r=g||m(this);r=f.requestInterceptor(r,a,o,q);var s=function(c){var d=c.data,e=f.responseExtractor(d,a,o,q)||n;"post"!==a||i[f.restangularFields.restangularCollection]?k.resolve(p(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):k.resolve(p(i,e,b))},t=function(a){f.errorInterceptor(a),k.reject(a)},u=a,v=_.extend({},h),w=f.isOverridenMethod(a);return w&&(u="post",v=_.extend(v,{"X-HTTP-Method-Override":a})),f.isSafe(a)?w?G.resource(this,c,v,l,b)[u]({}).then(s,t):G.resource(this,c,v,l,b)[u]().then(s,t):G.resource(this,c,v,l,b)[u](r).then(s,t),j(k.promise)}function u(a,b){return _.bind(t,this)("get",void 0,a,void 0,b)}function v(a,b){return _.bind(t,this)("remove",void 0,a,void 0,b)}function w(a,b){return _.bind(t,this)("put",void 0,a,void 0,b)}function x(a,b,c,d){return _.bind(t,this)("post",a,c,b,d)}function y(a,b){return _.bind(t,this)("head",void 0,a,void 0,b)}function z(a,b){return _.bind(t,this)("trace",void 0,a,void 0,b)}function A(a,b){return _.bind(t,this)("options",void 0,a,void 0,b)}function B(a,b){return _.bind(t,this)("patch",void 0,a,void 0,b)}function C(a,b,c,d,e){return _.bind(t,this)(a,b,c,e,d)}function D(a,b,c,d,e,f){var g;g="getList"===b?_.bind(s,this,c):_.bind(C,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function E(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var F={},G=new f.urlCreatorFactory[f.urlCreator];return G.setConfig(f),F.copy=_.bind(o,F),F.withConfig=_.bind(E,F),F.one=_.bind(h,F,null),F.all=_.bind(i,F,null),F.restangularizeElement=_.bind(p,F),F.restangularizeCollection=_.bind(q,F),F}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 65e3425e3f537426713086380da05c3b4374980c..600cd1632a4538eeeb10bca16556114dff85881f 100644 GIT binary patch delta 264 zcmeyrmFdw|Cf)#VW)?065b*E3IgwXE5J)-M*{@r{TFSrx!org$mWoUa3S~5%{J(U? z<^aa+*3A0)3X}KyYEE{rVV(TRSBNDwCpC9+y^W%1PL6`DLcCs5W?qU$Vor{Z0#rtN z@`f1U&Fr?@1U9$&{Z``uSz@?rd*tMf(lSQV&Hqd7gjJIC^7B${p_(&vl5~PRz+c z$OAd3@(PnLga~iW@cXUC0kZcm>!&}HvrEeu4JNKwvAL^kn$TvC&Z(?wDSAMYZK0NA z=%nbRXzHZs0ZoI6WrD;ezwejY{IySun;B@ Date: Tue, 25 Jun 2013 17:15:43 -0300 Subject: [PATCH 021/441] customDELETE now performs a remove fixes #135 --- CHANGELOG.md | 5 +++++ README.md | 2 ++ dist/restangular.zip | Bin 39650 -> 39650 bytes src/restangular.js | 3 ++- 4 files changed, 9 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 62dfbc27..1c3d2b7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +#1.0.0 +* First final release +* Added `one` and `all` to all collection methods +* + #0.8.9 * Fix call to `isOverridenMethod` in `setMethodOverriders`. diff --git a/README.md b/README.md index 5b5a8745..37c6ec8f 100644 --- a/README.md +++ b/README.md @@ -403,6 +403,8 @@ This are the methods that can be called in the Restangular object. * **patch([queryParams, headers])**: Does a PATCH * **putElement(idx, params, headers)**: Puts the element on the required index and returns a promise of the updated new array * **getRestangularUrl()**: Gets the URL of the current object. +* **one(route, id)**: Used for RequestLess connections and URL Building. See section below. +* **all(route)**: Used for RequestLess connections and URL Building. See section below. ### Custom methods * **customGET(path, [params, headers])**: Does a GET to the specific path. Optionally you can set params and headers. diff --git a/dist/restangular.zip b/dist/restangular.zip index 600cd1632a4538eeeb10bca16556114dff85881f..5acdf5be0358cd494ccd83fbe70cf221e872363e 100644 GIT binary patch delta 52 zcmaE~mFdw|Chh=lW)?065I8%LTZ!@PMm^I~#l$y#N3J delta 52 zcmaE~mFdw|Chh=lW)?065b&SKt;FcRQO~rL(SLJF>24K9|H%rojDTeDEC(PtWtJZR DhqDjK diff --git a/src/restangular.js b/src/restangular.js index 50d373c2..f31958e0 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -464,8 +464,9 @@ module.provider('Restangular', function() { elem.customOperation = _.bind(customFunction, elem); _.each(["put", "post", "get", "delete"], function(oper) { _.each(["do", "custom"], function(alias) { + var callOperation = oper === 'delete' ? 'remove' : oper; var name = alias + oper.toUpperCase(); - elem[name] = _.bind(customFunction, elem, oper); + elem[name] = _.bind(customFunction, elem, callOperation); }); }); elem.customGETLIST = _.bind(fetchFunction, elem); From 18b5b04abe5f460d4dfc38319edaf0792d004cb5 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Tue, 25 Jun 2013 17:33:48 -0300 Subject: [PATCH 022/441] Added fullResponse option to get all $http response Fixes #128 --- CHANGELOG.md | 3 ++- README.md | 4 ++++ dist/restangular.js | 26 +++++++++++++++++++++----- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 39650 -> 40582 bytes src/restangular.js | 23 +++++++++++++++++++---- 6 files changed, 47 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c3d2b7b..a4c5b745 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,8 @@ #1.0.0 * First final release * Added `one` and `all` to all collection methods -* +* Added `fullResponse` for getting the full `$http` response in every call +* Improved documentation on `addElemTransformer` #0.8.9 * Fix call to `isOverridenMethod` in `setMethodOverriders`. diff --git a/README.md b/README.md index 37c6ec8f..e9a68d1e 100644 --- a/README.md +++ b/README.md @@ -295,6 +295,10 @@ You can now Override HTTP Methods. You can set here the array of methods to over You can set default Query parameters to be sent with every request +#### fullResponse + +You can set fullResponse to true to get the whole response every time you do any request. The full response has the restangularized data in the `data` field, and also has the headers and config sent. By default, it's set to false. + #### defaultHeaders You can set default Headers to be sent with every request. diff --git a/dist/restangular.js b/dist/restangular.js index 2f366221..fa906fd5 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -235,6 +235,11 @@ module.provider('Restangular', function() { isCollection, route, Restangular); } + config.fullResponse = _.isUndefined(config.fullResponse) ? false : config.fullResponse; + object.setFullResponse = function(full) { + config.fullResponse = full; + } + //Internal values and functions @@ -459,6 +464,16 @@ module.provider('Restangular', function() { }); return restangularizePromise(deferred.promise, this[config.restangularFields.restangularCollection]); } + + function resolvePromise(deferred, response, data) { + if (config.fullResponse) { + return deferred.resolve(_.extend(response, { + data: data + })); + } else { + deferred.resolve(data); + } + } // Elements @@ -471,8 +486,9 @@ module.provider('Restangular', function() { elem.customOperation = _.bind(customFunction, elem); _.each(["put", "post", "get", "delete"], function(oper) { _.each(["do", "custom"], function(alias) { + var callOperation = oper === 'delete' ? 'remove' : oper; var name = alias + oper.toUpperCase(); - elem[name] = _.bind(customFunction, elem, oper); + elem[name] = _.bind(customFunction, elem, callOperation); }); }); elem.customGETLIST = _.bind(fetchFunction, elem); @@ -558,9 +574,9 @@ module.provider('Restangular', function() { processedData = _.extend(data, processedData); if (!__this[config.restangularFields.restangularCollection]) { - deferred.resolve(restangularizeCollection(__this, processedData, what)); + resolvePromise(deferred, response, restangularizeCollection(__this, processedData, what)); } else { - deferred.resolve(restangularizeCollection(null, processedData, __this[config.restangularFields.route])); + resolvePromise(deferred, response, restangularizeCollection(null, processedData, __this[config.restangularFields.route])); } }, function error(response) { config.errorInterceptor(response); @@ -586,9 +602,9 @@ module.provider('Restangular', function() { var resData = response.data; var elem = config.responseExtractor(resData, operation, route, fetchUrl) || resObj; if (operation === "post" && !__this[config.restangularFields.restangularCollection]) { - deferred.resolve(restangularizeElem(__this, elem, what)); + resolvePromise(deferred, response, restangularizeElem(__this, elem, what)); } else { - deferred.resolve(restangularizeElem(__this[config.restangularFields.parentResource], elem, __this[config.restangularFields.route])); + resolvePromise(deferred, response, restangularizeElem(__this[config.restangularFields.parentResource], elem, __this[config.restangularFields.route])); } }; diff --git a/dist/restangular.min.js b/dist/restangular.min.js index a6196fdc..438afafa 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -5,4 +5,4 @@ * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(G.fetchUrl,G,b),b.addRestangularMethod=_.bind(D,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),p(a,d,b)}function i(a,b){return q(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function n(a){a.customOperation=_.bind(C,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d=c+b.toUpperCase();a[d]=_.bind(C,a,b)})}),a.customGETLIST=_.bind(s,a),a.doGETLIST=a.customGETLIST}function o(a){var b=angular.copy(a);return p(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function p(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(u,d),d.getList=_.bind(s,d),d.put=_.bind(w,d),d.post=_.bind(x,d),d.remove=_.bind(v,d),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),n(d),f.transformElem(d,!1,c,F)}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(x,d,null),d.head=_.bind(y,d),d.trace=_.bind(z,d),d.putElement=_.bind(r,d),d.options=_.bind(A,d),d.patch=_.bind(B,d),d.getList=_.bind(s,d,null),n(d),f.transformElem(d,!0,c,F)}function r(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=o(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function s(a,b,e){var g=this,h=d.defer(),i="getList",k=G.fetchUrl(this,a),l=a||g[f.restangularFields.route];return f.requestInterceptor(null,i,l,k),G.resource(this,c,e,b,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?p(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):p(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?h.resolve(q(null,e,g[f.restangularFields.route])):h.resolve(q(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function t(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},n=g||this,o=b||this[f.restangularFields.route],q=G.fetchUrl(this,b),r=g||m(this);r=f.requestInterceptor(r,a,o,q);var s=function(c){var d=c.data,e=f.responseExtractor(d,a,o,q)||n;"post"!==a||i[f.restangularFields.restangularCollection]?k.resolve(p(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):k.resolve(p(i,e,b))},t=function(a){f.errorInterceptor(a),k.reject(a)},u=a,v=_.extend({},h),w=f.isOverridenMethod(a);return w&&(u="post",v=_.extend(v,{"X-HTTP-Method-Override":a})),f.isSafe(a)?w?G.resource(this,c,v,l,b)[u]({}).then(s,t):G.resource(this,c,v,l,b)[u]().then(s,t):G.resource(this,c,v,l,b)[u](r).then(s,t),j(k.promise)}function u(a,b){return _.bind(t,this)("get",void 0,a,void 0,b)}function v(a,b){return _.bind(t,this)("remove",void 0,a,void 0,b)}function w(a,b){return _.bind(t,this)("put",void 0,a,void 0,b)}function x(a,b,c,d){return _.bind(t,this)("post",a,c,b,d)}function y(a,b){return _.bind(t,this)("head",void 0,a,void 0,b)}function z(a,b){return _.bind(t,this)("trace",void 0,a,void 0,b)}function A(a,b){return _.bind(t,this)("options",void 0,a,void 0,b)}function B(a,b){return _.bind(t,this)("patch",void 0,a,void 0,b)}function C(a,b,c,d,e){return _.bind(t,this)(a,b,c,e,d)}function D(a,b,c,d,e,f){var g;g="getList"===b?_.bind(s,this,c):_.bind(C,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function E(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var F={},G=new f.urlCreatorFactory[f.urlCreator];return G.setConfig(f),F.copy=_.bind(o,F),F.withConfig=_.bind(E,F),F.one=_.bind(h,F,null),F.all=_.bind(i,F,null),F.restangularizeElement=_.bind(p,F),F.restangularizeCollection=_.bind(q,F),F}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route];return f.requestInterceptor(null,i,l,k),H.resource(this,c,e,b,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);s=f.requestInterceptor(s,a,p,r);var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},h),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,l,b)[v]({}).then(t,u):H.resource(this,c,w,l,b)[v]().then(t,u):H.resource(this,c,w,l,b)[v](s).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",void 0,a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 5acdf5be0358cd494ccd83fbe70cf221e872363e..9c4b76f2be6387dbb03075d6b0b80845c737a065 100644 GIT binary patch delta 2195 zcma)8U2NM_6pp*4VYDRupSXF-lZ(|s5hKOQShpq>9V`2Rv3Bho`)2W$+KzwH zjJDba653DOr9E4_6(RP51Wycwp9cgQ5-$h|O}wE=NK6P#LTKy_gwVK7;xrY5HIk$2 z?|$drbIpGSYO(u#yA{xfRewdW%+{J}Kc(nuWBt4rQDpy{D8RKxy#EQgJOo7_A5q=4GKpkp< zhHyI!4L7cr1XF<1qs?$5*Z`*nIw3#cE9CpXq2N~H(N3D@c{(KFG&XUFL?fi*aWzYZ z5n9!-4lm0|;I-~p;CmRP85`9_05|daZ5H=dv8d(h?fitk#UnLs8A{l|5TutVM0{_Of+WI(` z#HN@!pr=tB{yY<;b`>_At)Zw4be`*^^g{I9U(^UnAd#Kav1#cFom}NdRQR_l5@^y+ zeMFpQ*$A^j5LuK}Wr^-)rya*=1-8u$bgB$-P~b$%Fx7FAXkD;{P6CjSiOP1u)tON~ zSdvPR$R-gbfwsjGj3f}|#c+Z%)dL!_>l28y* z2GaP%)D--Ez76uPxZ_CYSA@$H2?-V%Hd`savb_eMB+ATK*f0ka6YC<@OjTzLq6Q7= zY;RW3X%ntNkH>zUno{9ch!7W!lT&4&`(nJQJZ5BsQG#Wskp*)XyI;!k0-7MHDYwAM zX_R77j_f8Id$OdZ$`V#~V>6{nMAW_IqRDO9!esfNov>iF^#s&kLML<4c(IBs;$`VH zBAP&Hvg>g6Ff%#La%KvXgCUEJ{2z0zJfn(;jxigKb6V+EfP0r{68fJmu`syULPqo= z3gj4pc;b|Qxh5@SN1bJYq%MG4e4IJ~GmCy=@!ld0?j_sy=He63UmUeBh2d;*G_v$$ zYu|m>gLjw0)K2(zsjb6Vn`}#xfrHL; zoWx<%74BHv?udQG>y=5eD8`AZcETwuji{GE6SA2qQJjhX(uAs1N;HLHW$DK_auqp5 zc?E_Bv(@L|nbHCv4EwzfrWY}|cZIHT&p=>#Yq9^Yd_BOC<)`V@SAxs6vG}p!{B6lW MVVSM{>>V5U2lH9}`v3p{ delta 1557 zcma)+Urbw79LIYrbVjhQ(vC4VXgk1r-Qi|LOcc^p2DID2NZbq%R!q4){j;_A-rhfL zaWwToOr`@{eyqSPEb+y-7vgM;(ZskV?qLrkKInr!x;K5<;*&8ko_otJor#7vJvryo z@BQ8HIltfeeekXI*DtNDljBb{J!8>7yVpyt9>?zWpU4! zb2i9tABC0BOyj!hoqM&p4(?2}L6LjoUu#>nBhv1)>z?|*`D$jV+hSSjuAa&L&z9>5TA|c;9?0kZc&?6{JLgdL8g;`FO6(JQIyEJkB;w4id!yiS465vG1 zLjwCtlVmKGW(z8cFet*turiU5mAbk{MYT?{dqmh5W3sb4<7qNPSrUVnqk@zgOX3tAL7slZp#Z#Jng$yj zE)YkESCdJ7M+bC3wy4L#e0`_Vp0xuyYdE{US~BFii~n+c+Hk$IdK7+v07;5xZGw`4 zU+bfSu(fuXjDN1(wu&?imyfJ2KL-zP>Ph?kX0RpBN>~<>8BC|)wepKktYhVikXkzg z_sTsjyf3!6sKgU865w&UyC?12FE`rYq~au9lromgkmQTPCt;^uBBdmtG&7V5OKur1 zuMZs3my3%$tgjEYUacD-_NWcR-rwuq_C}sSm{cQ^M~V;9W$#J-zblwi=rCcbFN`uI zw>YO@Qn}aiD9)fPhp@E#=MQ141B(U3R!>9c(*EXxV8ljWl)m5X;ux9 zI1H=AF;B}#VFv$Cc~G6yAVgPa*Hu=Ogj7PtOg^geoL;wX6&`OoTNI?9C_{T=7!GS) zR7R(i0^e^U*x7WEnN4Hh(PlFYXgWWyxv7OcO+kAJ5}L00PCEs+_1S8r4}Q~J_Ig<3 zI)Fp#BzIq^93$EfD=$!^@M-1L^JKevmN{n7Yz6SJQlZA6ur*{0_{i}F;qDfDGRVqU z84>tsB1T6U6ks_)TrjVgfC2=8W4mo&%$TwQU%#qx6xh2|0XCdWn$INmF-&iF+QeFn z{%pr-Q<64NUc!nh@or3$4izFjie`o;$0@7RVzzI%zuj;2%KiQgO}AclKiNJlmUg4v Qo5PF>Q@0pfo2G+*0EZYC_y7O^ diff --git a/src/restangular.js b/src/restangular.js index f31958e0..8efc00a3 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -228,6 +228,11 @@ module.provider('Restangular', function() { isCollection, route, Restangular); } + config.fullResponse = _.isUndefined(config.fullResponse) ? false : config.fullResponse; + object.setFullResponse = function(full) { + config.fullResponse = full; + } + //Internal values and functions @@ -452,6 +457,16 @@ module.provider('Restangular', function() { }); return restangularizePromise(deferred.promise, this[config.restangularFields.restangularCollection]); } + + function resolvePromise(deferred, response, data) { + if (config.fullResponse) { + return deferred.resolve(_.extend(response, { + data: data + })); + } else { + deferred.resolve(data); + } + } // Elements @@ -552,9 +567,9 @@ module.provider('Restangular', function() { processedData = _.extend(data, processedData); if (!__this[config.restangularFields.restangularCollection]) { - deferred.resolve(restangularizeCollection(__this, processedData, what)); + resolvePromise(deferred, response, restangularizeCollection(__this, processedData, what)); } else { - deferred.resolve(restangularizeCollection(null, processedData, __this[config.restangularFields.route])); + resolvePromise(deferred, response, restangularizeCollection(null, processedData, __this[config.restangularFields.route])); } }, function error(response) { config.errorInterceptor(response); @@ -580,9 +595,9 @@ module.provider('Restangular', function() { var resData = response.data; var elem = config.responseExtractor(resData, operation, route, fetchUrl) || resObj; if (operation === "post" && !__this[config.restangularFields.restangularCollection]) { - deferred.resolve(restangularizeElem(__this, elem, what)); + resolvePromise(deferred, response, restangularizeElem(__this, elem, what)); } else { - deferred.resolve(restangularizeElem(__this[config.restangularFields.parentResource], elem, __this[config.restangularFields.route])); + resolvePromise(deferred, response, restangularizeElem(__this[config.restangularFields.parentResource], elem, __this[config.restangularFields.route])); } }; From eda4e961f6af4cbc48d1bfc832bf487c50d70a59 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Tue, 25 Jun 2013 18:10:46 -0300 Subject: [PATCH 023/441] Added fullRequestInterceptor Can modify headers and params Fixes #114 --- README.md | 21 ++++++++++++++++++++ dist/restangular.js | 43 ++++++++++++++++++++++++++++++---------- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 40582 -> 41718 bytes src/restangular.js | 43 ++++++++++++++++++++++++++++++---------- 5 files changed, 86 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index e9a68d1e..a33e55c7 100644 --- a/README.md +++ b/README.md @@ -267,6 +267,16 @@ The requestInterceptor is called before sending any data to the server. It's a f * **what**: The model that's being requested. It can be for example: `accounts`, `buildings`, etc. * **url**: The relative URL being requested. For example: `/api/v1/accounts/123` +#### fullRequestInterceptor +The fullRequestInterceptor is similar to the `requestInterceptor` but more powerful. It lets you change the element, the request parameters and the headers as well. + +It's a function that receives the same as the `requestInterceptor` plus the headers and the query parameters (in that order). + +It must return an object with the following properties: +* **headers**: The headers to send +* **params**: The request parameters to send +* **element**: The element to send + #### errorInterceptor The errorInterceptor is called whenever there's an error. It's a function that receives the response as a parameter. @@ -329,11 +339,22 @@ app.config(function(RestangularProvider) { RestangularProvider.setRequestSuffix('.json'); + // Use Request interceptor RestangularProvider.setRequestInterceptor(function(element, operation, route, url) { delete elem.name; return elem; }); + // Or full request interceptor, its powerfull brother + RestangularProvider.setFullRequestInterceptor(function(element, operation, route, url, headers, params) { + delete elem.name; + return { + element: elem, + params: _.extend(params, {single: true}), + headers: headers + }; + }); + RestangularProvider.addElementTransformer('accounts', false,function(elem) { elem.accountName = 'Changed'; return elem; diff --git a/dist/restangular.js b/dist/restangular.js index fa906fd5..66f14ef1 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -147,14 +147,31 @@ module.provider('Restangular', function() { /** * Request interceptor is called before sending an object to the server. */ - config.requestInterceptor = config.requestInterceptor || function(element) { - return element; + config.fullRequestInterceptor = config.fullRequestInterceptor || function(element, operation, + path, url, headers, params) { + return { + element: element, + headers: headers, + params: params + }; } object.setRequestInterceptor = function(interceptor) { - config.requestInterceptor = interceptor; + config.fullRequestInterceptor = function(elem, operation, path, url, headers, params) { + return { + headers: headers, + params: params, + element: interceptor(elem, operation, path, url) + } + }; + } + + object.setFullRequestInterceptor = function(interceptor) { + config.fullRequestInterceptor = interceptor; } + + config.errorInterceptor = config.errorInterceptor || function() {}; object.setErrorInterceptor = function(interceptor) { @@ -557,9 +574,10 @@ module.provider('Restangular', function() { var whatFetched = what || __this[config.restangularFields.route]; - config.requestInterceptor(null, operation, whatFetched, url) + var request = config.fullRequestInterceptor(null, operation, + whatFetched, url, headers || {}, reqParams || {}); - urlHandler.resource(this, $http, headers, reqParams, what).getList().then(function(response) { + urlHandler.resource(this, $http, request.headers, request.params, what).getList().then(function(response) { var resData = response.data; var data = config.responseExtractor(resData, operation, whatFetched, url); var processedData = _.map(data, function(elem) { @@ -595,8 +613,8 @@ module.provider('Restangular', function() { var fetchUrl = urlHandler.fetchUrl(this, what); var callObj = obj || stripRestangular(this); - callObj = config.requestInterceptor(callObj, operation, route, fetchUrl) - + request = config.fullRequestInterceptor(callObj, operation, route, fetchUrl, + headers || {}, resParams || {}); var okCallback = function(response) { var resData = response.data; @@ -615,7 +633,7 @@ module.provider('Restangular', function() { }; // Overring HTTP Method var callOperation = operation; - var callHeaders = _.extend({}, headers); + var callHeaders = _.extend({}, request.headers); var isOverrideOperation = config.isOverridenMethod(operation); if (isOverrideOperation) { callOperation = 'post'; @@ -624,12 +642,15 @@ module.provider('Restangular', function() { if (config.isSafe(operation)) { if (isOverrideOperation) { - urlHandler.resource(this, $http, callHeaders, resParams, what)[callOperation]({}).then(okCallback, errorCallback); + urlHandler.resource(this, $http, callHeaders, request.params, + what)[callOperation]({}).then(okCallback, errorCallback); } else { - urlHandler.resource(this, $http, callHeaders, resParams, what)[callOperation]().then(okCallback, errorCallback); + urlHandler.resource(this, $http, callHeaders, request.params, + what)[callOperation]().then(okCallback, errorCallback); } } else { - urlHandler.resource(this, $http, callHeaders, resParams, what)[callOperation](callObj).then(okCallback, errorCallback); + urlHandler.resource(this, $http, callHeaders, request.params, + what)[callOperation](request.element).then(okCallback, errorCallback); } return restangularizePromise(deferred.promise); diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 438afafa..ffa6d3ea 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -5,4 +5,4 @@ * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.requestInterceptor=b.requestInterceptor||function(a){return a},a.setRequestInterceptor=function(a){b.requestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route];return f.requestInterceptor(null,i,l,k),H.resource(this,c,e,b,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);s=f.requestInterceptor(s,a,p,r);var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},h),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,l,b)[v]({}).then(t,u):H.resource(this,c,w,l,b)[v]().then(t,u):H.resource(this,c,w,l,b)[v](s).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",void 0,a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);request=f.fullRequestInterceptor(s,a,p,r,h||{},l||{});var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},request.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,request.params,b)[v]({}).then(t,u):H.resource(this,c,w,request.params,b)[v]().then(t,u):H.resource(this,c,w,request.params,b)[v](request.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",void 0,a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 9c4b76f2be6387dbb03075d6b0b80845c737a065..04edc9f768e5bb3dfce852e63d72c3262f0716b2 100644 GIT binary patch delta 1218 zcmaJ>OH30{6m3hf(v(tQXsLocK9&wXD}FFqL4ykvi4h4F32`xPUpqC!v`(i;(l!xe zTp6KW6-b0cP29LJX4V=tvbXMZrHL`RQ4=7k!{!D}?&qy9$?d5cB)nqhdJdOGpeSDVOj+yq$tlq;6z6RBiKOANQ} zJcv;`Lj*=lrFo2;sOn@Gk;Nz{a2TY@>l`j?RDm$gOG8wKt1tDlm2hV zZiVe$fn3UwtcZqC6`QA~yP=GI{g+ur93f(iCGl$VP@#bGMU3S7ag{|a0cZD6ur%Gh zO~(zHTpNju^kTZ~*sSkEX27OW-XhcD@Kw5GtGY0gLCBo1m3+}pHCqj2@Nlj0q026> zC2dc_`Kl?2J3W&3D(vMCyMZ8A!t`{;rl|{h*^x2X1P(6Fp84cL=5T$bg@{(Oejl4 z#XT}qr)C{usDv>^-4T(;M1d>hXWYY#kHkFl^;7#>; zT?MKBPM@toXV8QkT=u&#t3q;0l+G=8SdCi-2IN+XZi9PmdHA_P|CwrE?d_?)g`@P$ u++VUur&s6fwnzy!*7mAORUR9#ukT0I;#n*{^=&djEDuxb^p@TSO5!&`HLflI delta 510 zcmex%l&Nhm6HkCQGYc032(b1{%gvmcS2Ec~vH~g}BdsyHj-7q-gLHw(RuWv3XG#lBj+Wrrd_nrS z{p11`kmili%9G_{1sS;}f7B74?31m?n~|EBl3G-(qfnGu7_d1f<|4aLa$-)7e^Qo$ ztwM5sURq|lUeV;>6jMe`upWUd;mIJZpvJQKWy(|L$%_lbCqD@1-25%$5Fw=W?n59aNfHT;iEm zl3J9UT2PW-WSgXiCOA2qwMx!JnvsfotCsikDv&u{@Ce~tGklNVUlAD`m%QG@&Ox`f3mN93t^;}IL zSu|IjGe;*$GrBBRqj>Y)xn(R&tUZ%W7a5{O(&Umw#tNW#L->J#K^z>XFhZ?ja(%Vr O Date: Tue, 25 Jun 2013 18:22:26 -0300 Subject: [PATCH 024/441] Suggested usage of addElementTransformer instead of onElemRestangularized Fixes #142 --- README.md | 63 ++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 44 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index a33e55c7..2dafaeb2 100644 --- a/README.md +++ b/README.md @@ -231,8 +231,24 @@ This are the fields that you want to save from your parent resources if you need #### urlCreator This is the factory that will create URLs based on the resources. For the time being, only Path UrlCreator is implemented. This means that if you have a resource names Building which is a child of Account, the URL to fetch this will be `/accounts/123/buildings`. In the future, I'll implement more UrlCreator like QueryParams UrlCreator. +#### addElementTransformer +This is a hook. After each element has been "restangularized" (Added the new methods from Restangular), the corresponding transformer will be called if it fits. + +This should be used to add your own methods / functions to entities of certain types. + +You can add as many element transformers as you want. The signature of this method can be one of the following: + +* **addElementTransformer(route, transformer)**: Transformer is called with all elements that have been restangularized, no matter if they're collections or not. + +* **addElementTransformer(route, isCollection, transformer)**: Transformer is called with all elements that have been restangularized and match the specification regarding if it's a collection or not (true | false) + + #### onElemRestangularized This is a hook. After each element has been "restangularized" (Added the new methods from Restangular), this will be called. It means that if you receive a list of objects in one call, this method will be called first for the collection and then for each element of the collection. + +**I favor the usage of `addElementTransformer` instead of `onElemRestangularized` whenever possible as the implementation is much cleaner.** + + This callback is a function that has 3 parameters: * **elem**: The element that has just been restangularized. Can be a collection or a single element. @@ -242,12 +258,6 @@ This callback is a function that has 3 parameters: This can be used together with `addRestangularMethod` (Explained later) to add custom methods to an element -#### addElementTransformer -You can add as many element transformers as you want. The signature of this method can be one of the following: - -* **addElementTransformer(route, transformer)**: Transformer is called with all elements that have been restangularized, no matter if they're collections or not. - -* **addElementTransformer(route, isCollection, transformer)**: Transformer is called with all elements that have been restangularized and match the specification regarding if it's a collection or not (true | false) #### responseInterceptor (or responseExtractor. It's an Alias) The responseInterceptor is called after we get each response from the server. It's a function that receives 4 arguments: @@ -328,6 +338,11 @@ app.config(function(RestangularProvider) { return response.data; }); + RestangularProvider.addElementTransformer('accounts', false, function(elem) { + elem.accountName = 'Changed'; + return elem; + }); + RestangularProvider.setDefaultHttpFields({cache: true}); RestangularProvider.setMethodOverriders(["put", "patch"]); @@ -355,10 +370,6 @@ app.config(function(RestangularProvider) { }; }); - RestangularProvider.addElementTransformer('accounts', false,function(elem) { - elem.accountName = 'Changed'; - return elem; - }); }); ```` @@ -503,19 +514,29 @@ Restangular.one("accounts", 123).one("buildings", 456).remove(); ## Creating new Restangular Methods -Let's assume that your API needs some custom methods to work. If that's the case, always calling customGET or customPOST for that method with all parameters is a pain in the ass. That's why every element has a `addRestangularMethod` method. This can be used together with the hook `setOnElemRestangularized` to do some neat stuff. Let's see an example to learn this: +Let's assume that your API needs some custom methods to work. If that's the case, always calling customGET or customPOST for that method with all parameters is a pain in the ass. That's why every element has a `addRestangularMethod` method. + +This can be used together with the hook `addElementTransformer` to do some neat stuff. Let's see an example to learn this: ````javascript //In your app configuration (config method) -RestangularProvider.setOnElemRestangularized(function(elem, isCollection, route) { - if (!isCollection && route === "buildings") { + +// It will transform all building elements, NOT collections +RestangularProvider.addElementTransformer('buildings', false, function(building) { // This will add a method called evaluate that will do a get to path evaluate with NO default // query params and with some default header // signature is (name, operation, path, params, headers, elementToPost) - elem.addRestangularMethod('evaluate', 'get', 'evaluate', undefined, {'myHeader': 'value'}); - } - return elem; -}) + + building.addRestangularMethod('evaluate', 'get', 'evaluate', undefined, {'myHeader': 'value'}); +}); + +RestangularProvider.addElementTransformer('users', true, function(users) { + // This will add a method called evaluate that will do a get to path evaluate with NO default + // query params and with some default header + // signature is (name, operation, path, params, headers, elementToPost) + + users.addRestangularMethod('login', 'post', 'login'); +}); // Then, later in your code you can do the following: @@ -523,10 +544,14 @@ RestangularProvider.setOnElemRestangularized(function(elem, isCollection, route) //Signature for this "custom created" methods is (params, headers, elem) // If something is set to any of this variables, the default set in the method creation will be overrided // If nothing is set, then the defaults are sent -building.evaluate({myParam: 'param'}); +Restangular.one('building', 123).evaluate({myParam: 'param'}); //GET to /buildings/123/evaluate?myParam=param with headers myHeader: specialHeaderCase -building.evaluate({myParam: 'param'}, {'myHeader': 'specialHeaderCase'}); +Restangular.one('building', 123).evaluate({myParam: 'param'}, {'myHeader': 'specialHeaderCase'}); + +Restangular.all('users').login(); + + ```` From 75956fd1ca33606e6547230561ec23c34f5f4cdf Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Tue, 25 Jun 2013 18:23:13 -0300 Subject: [PATCH 025/441] v1.0.0 --- bower.json | 2 +- dist/restangular.js | 2 +- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 41718 -> 41718 bytes package.json | 2 +- 5 files changed, 4 insertions(+), 4 deletions(-) diff --git a/bower.json b/bower.json index 35e7ebaf..19c46f99 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "0.8.9", + "version": "1.0.0", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { diff --git a/dist/restangular.js b/dist/restangular.js index 66f14ef1..3160d5b5 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.9 - 2013-06-25 + * @version v1.0.0 - 2013-06-25 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.min.js b/dist/restangular.min.js index ffa6d3ea..bacf7ba5 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v0.8.9 - 2013-06-25 + * @version v1.0.0 - 2013-06-25 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.zip b/dist/restangular.zip index 04edc9f768e5bb3dfce852e63d72c3262f0716b2..eaeb3b8dd49140e434483466ec8f8e81737541fe 100644 GIT binary patch delta 106 zcmex%l`_&<8Oiw0FHeF;0*Eu=kwJ-M_x6(YC!eszc%Q`p4Gri%>WIw$8XvP7s|zsMZ`PfsO+ diff --git a/package.json b/package.json index a5760875..02a83204 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "restangular", "description": "Restfull Resources service for AngularJS apps", - "version": "0.8.9", + "version": "1.0.0", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", "author": "Martin Gontovnikas ", From 93d22b9c8cadeba983ac0528b9864d62272b2888 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Tue, 25 Jun 2013 18:25:24 -0300 Subject: [PATCH 026/441] Fixed bug on restangularizeElement Fixes #139 --- dist/restangular.zip | Bin 41718 -> 41718 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/dist/restangular.zip b/dist/restangular.zip index eaeb3b8dd49140e434483466ec8f8e81737541fe..97f44435b2d33eb4d25a4a74e506d9d47931cb89 100644 GIT binary patch delta 58 zcmex%lQ7aeu F0sszE6EOe) delta 58 zcmex%l Date: Tue, 25 Jun 2013 18:26:00 -0300 Subject: [PATCH 027/441] v1.0.1 --- CHANGELOG.md | 2 +- bower.json | 2 +- dist/restangular.js | 2 +- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 41718 -> 41718 bytes package.json | 2 +- 6 files changed, 5 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a4c5b745..a9f26662 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -#1.0.0 +#1.0.1 * First final release * Added `one` and `all` to all collection methods * Added `fullResponse` for getting the full `$http` response in every call diff --git a/bower.json b/bower.json index 19c46f99..ee82fe12 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "1.0.0", + "version": "1.0.1", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { diff --git a/dist/restangular.js b/dist/restangular.js index 3160d5b5..e38e0a7f 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.0 - 2013-06-25 + * @version v1.0.1 - 2013-06-25 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.min.js b/dist/restangular.min.js index bacf7ba5..27d6d20b 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.0 - 2013-06-25 + * @version v1.0.1 - 2013-06-25 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.zip b/dist/restangular.zip index 97f44435b2d33eb4d25a4a74e506d9d47931cb89..7a18e7d66c43e87cff4f6a9da62eff1adac826ba 100644 GIT binary patch delta 96 zcmex%lmSCe#1` delta 96 zcmex%l", From fd415fe9229fcf25bcaa139d149864087a35542d Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Tue, 25 Jun 2013 18:32:20 -0300 Subject: [PATCH 028/441] Restangular can be configured through service as well now Fixes #125 --- README.md | 2 +- dist/restangular.js | 2 +- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 41718 -> 41776 bytes src/restangular.js | 2 +- 5 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 2dafaeb2..255444dd 100644 --- a/README.md +++ b/README.md @@ -217,7 +217,7 @@ account.customPOST("messages", {param: "myParam"}, {}, {name: "My Message"}) ### Properties Restangular comes with defaults for all of it's properties but you can configure them. **So, if you don't need to configure something, there's no need to add the configuration.** -You can set all this configurations in **`RestangularProvider` to change the global configuration** or you can **use the withConfig method in Restangular service to create a new Restangular service with some scoped configuration**. Check the section on this later. +You can set all this configurations in **`RestangularProvider` or `Restangular` service to change the global configuration** or you can **use the withConfig method in Restangular service to create a new Restangular service with some scoped configuration**. Check the section on this later. #### baseUrl The base URL for all calls to your API. For example if your URL for fetching accounts is http://example.com/api/v1/accounts, then your baseUrl is `/api/v1`. The default baseUrl is an empty string which resolves to the same url that AngularJS is running, so you can also set an absolute url like `http://api.example.com/api/v1` if you need do set another domain. diff --git a/dist/restangular.js b/dist/restangular.js index e38e0a7f..47e2e26f 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -722,7 +722,7 @@ module.provider('Restangular', function() { } - + Configurer.init(service, globalConfiguration); service.copy = _.bind(copyRestangularizedElement, service); diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 27d6d20b..b11d7ca6 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -5,4 +5,4 @@ * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);request=f.fullRequestInterceptor(s,a,p,r,h||{},l||{});var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},request.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,request.params,b)[v]({}).then(t,u):H.resource(this,c,w,request.params,b)[v]().then(t,u):H.resource(this,c,w,request.params,b)[v](request.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",void 0,a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);request=f.fullRequestInterceptor(s,a,p,r,h||{},l||{});var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},request.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,request.params,b)[v]({}).then(t,u):H.resource(this,c,w,request.params,b)[v]().then(t,u):H.resource(this,c,w,request.params,b)[v](request.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",void 0,a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,b),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 7a18e7d66c43e87cff4f6a9da62eff1adac826ba..155a3433f4f8cf729f3e20c7fdc0af8390a3bbda 100644 GIT binary patch delta 175 zcmex%lxf2;CY}IqW)?065MZ7%kw=l2dCE;E?=Rc$+g39$*lx6%R5AG{BR`i$acWUn zW^$^I!eqH>g~>c_!kb@JG&6x!Co;+1o~_2fFne=V^=DPCM7_+s%n}WEoutXx3r{dH sPnm4G$Pm@o$;FFI6hIciwF0$^gB<}QCRR_bua=zrV37b@;v$eB04&Nk(f|Me delta 157 zcmdmRjOp7^CY}IqW)?065OA10kw;O;Ve(C Date: Tue, 25 Jun 2013 18:33:23 -0300 Subject: [PATCH 029/441] v1.0.2 --- CHANGELOG.md | 3 ++- bower.json | 2 +- dist/restangular.js | 2 +- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 41776 -> 41776 bytes package.json | 2 +- 6 files changed, 6 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a9f26662..3f3a918a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,9 @@ -#1.0.1 +#1.0.2 * First final release * Added `one` and `all` to all collection methods * Added `fullResponse` for getting the full `$http` response in every call * Improved documentation on `addElemTransformer` +* Configuration can be set globally on either `RestangularProvider` or `Restangular` #0.8.9 * Fix call to `isOverridenMethod` in `setMethodOverriders`. diff --git a/bower.json b/bower.json index ee82fe12..67143414 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "1.0.1", + "version": "1.0.2", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { diff --git a/dist/restangular.js b/dist/restangular.js index 47e2e26f..62070fca 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.1 - 2013-06-25 + * @version v1.0.2 - 2013-06-25 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.min.js b/dist/restangular.min.js index b11d7ca6..b6bed9de 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.1 - 2013-06-25 + * @version v1.0.2 - 2013-06-25 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.zip b/dist/restangular.zip index 155a3433f4f8cf729f3e20c7fdc0af8390a3bbda..2b804aa8618ad79fe16ad754b5c1e84068f841d9 100644 GIT binary patch delta 124 zcmdmRjA_F$Chh=lW)?065Rjb6tt2El<)%~Gk0orj)eHsTMV4R=NYmt( Gi`)UWe<#EM delta 124 zcmdmRjA_F$Chh=lW)?065MZ9jtt7-e<))MOm+kj$s~H$TSeRil<6_~7K^}~TlX+{l zZVq7dt^zAcWRkl*TaAGMgvCLMBqtxMc4IW$%v+P7#>hN5Z;=rP%&^HT7FmKhAWf5B HE^-F|@z*HU diff --git a/package.json b/package.json index 04d4ef23..298c9915 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "restangular", "description": "Restfull Resources service for AngularJS apps", - "version": "1.0.1", + "version": "1.0.2", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", "author": "Martin Gontovnikas ", From d9fb5737e5f80a9c512693348ad7edd56e4e0018 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Tue, 25 Jun 2013 19:10:30 -0300 Subject: [PATCH 030/441] Added `run` suggestion for configuration As propsed in comment on #142 --- README.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 255444dd..817dbba4 100644 --- a/README.md +++ b/README.md @@ -328,8 +328,10 @@ You can set default Headers to be sent with every request. If all of your requests require to send some suffix to work, you can set it here. For example, if you need to send the format like `/users/123.json`you can add that `.json` to the suffix using the `setRequestSuffix`method ### How to configure them globally -You can configure this properties inside the config method of your app +You can do this configurations in either the `config` or the `run` method. If your configurations don't need any other services, then I'd recommend you do them in the `config`. If your configurations depend on other services, you can configure them in the `run` using `Restangular` instead of `RestangularProvider` + +#### Configuring in the `config` ````javascript app.config(function(RestangularProvider) { RestangularProvider.setBaseUrl('/api/v1'); @@ -374,6 +376,15 @@ app.config(function(RestangularProvider) { ```` +#### Configuring in the `run` + +````javascript +// Here I inject the service BaseUrlCalculator which I need +app.run(function(Restangular, BaseUrlCalculator) { + Restangular.setBaseUrl(BaseUrlCalculator.calculate()); +}); +```` + ### How to create a Restangular service with a different configuration from the global one Let's assume that for most requests you need some configuration (The global one), and for just a bunch of methods you need another configuration. In that case, you'll need to create another Restangular service with this particular configuration. This scoped configuration will inherit all defaults from the global one. Let's see how. From 7f0e30ead6bd11d50aa77b1520c5e2de1ad8e3d4 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Wed, 26 Jun 2013 00:10:14 -0300 Subject: [PATCH 031/441] restangularizeElement can now set parent to null --- bower.json | 2 +- dist/restangular.js | 8 +++++--- dist/restangular.min.js | 4 ++-- dist/restangular.zip | Bin 41776 -> 41894 bytes package.json | 2 +- src/restangular.js | 6 ++++-- 6 files changed, 13 insertions(+), 9 deletions(-) diff --git a/bower.json b/bower.json index 67143414..484908c7 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "1.0.2", + "version": "1.0.3", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { diff --git a/dist/restangular.js b/dist/restangular.js index 62070fca..22a88650 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.2 - 2013-06-25 + * @version v1.0.3 - 2013-06-26 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT @@ -275,7 +275,7 @@ module.provider('Restangular', function() { BaseCreator.prototype.parentsArray = function(current) { var parents = []; - while(!_.isUndefined(current)) { + while(current) { parents.push(current); current = current[this.config.restangularFields.parentResource]; } @@ -434,7 +434,9 @@ module.provider('Restangular', function() { _.values( _.pick(config.restangularFields, ['id', 'route', 'parentResource']) ), config.extraFields ); - elem[config.restangularFields.parentResource]= _.pick(parent, restangularFieldsForParent); + elem[config.restangularFields.parentResource] = _.pick(parent, restangularFieldsForParent); + } else { + elem[config.restangularFields.parentResource] = null; } return elem; } diff --git a/dist/restangular.min.js b/dist/restangular.min.js index b6bed9de..d795c1b8 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.2 - 2013-06-25 + * @version v1.0.3 - 2013-06-26 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];!_.isUndefined(a);)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);request=f.fullRequestInterceptor(s,a,p,r,h||{},l||{});var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},request.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,request.params,b)[v]({}).then(t,u):H.resource(this,c,w,request.params,b)[v]().then(t,u):H.resource(this,c,w,request.params,b)[v](request.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",void 0,a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,b),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);request=f.fullRequestInterceptor(s,a,p,r,h||{},l||{});var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},request.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,request.params,b)[v]({}).then(t,u):H.resource(this,c,w,request.params,b)[v]().then(t,u):H.resource(this,c,w,request.params,b)[v](request.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",void 0,a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,b),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 2b804aa8618ad79fe16ad754b5c1e84068f841d9..923ae8a0acc5a281999271e0bd69b8137795cc6c 100644 GIT binary patch delta 286 zcmdmRjA_|%Cf)#VW)?065O89=HIY|A2uL~Is=m@Zxtf6igoPO-y z9IqrfdB2p%};ty#i@ZPRkQwNO$pwoH fcu~AEdF>(-d5{RIRba0}iRY6RYq4El1mXbzyd_tP delta 253 zcmZ2>oN2=`Cf)#VW)?065Rja5b0V(-FOYId`>}-0wwi&#cA`}RpOJ#Df{}rtv95uc zu94~Ff|?bZ0~kX!#TDcAGK)j=Qc}}0^HNhZl1qzv4Bg7|&W_F_H=H@PD_RZTS r>IyOg9XR>fA_G*1PF7xQA`fyp+-#uv;$VNlh>4TS7HhF3E&}lZX{t>b diff --git a/package.json b/package.json index 298c9915..6fd37978 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "restangular", "description": "Restfull Resources service for AngularJS apps", - "version": "1.0.2", + "version": "1.0.3", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", "author": "Martin Gontovnikas ", diff --git a/src/restangular.js b/src/restangular.js index 96f34a76..862910e2 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -268,7 +268,7 @@ module.provider('Restangular', function() { BaseCreator.prototype.parentsArray = function(current) { var parents = []; - while(!_.isUndefined(current)) { + while(current) { parents.push(current); current = current[this.config.restangularFields.parentResource]; } @@ -427,7 +427,9 @@ module.provider('Restangular', function() { _.values( _.pick(config.restangularFields, ['id', 'route', 'parentResource']) ), config.extraFields ); - elem[config.restangularFields.parentResource]= _.pick(parent, restangularFieldsForParent); + elem[config.restangularFields.parentResource] = _.pick(parent, restangularFieldsForParent); + } else { + elem[config.restangularFields.parentResource] = null; } return elem; } From f3cbd451af4ec7fdd9acc51d4005a9ccd0818691 Mon Sep 17 00:00:00 2001 From: Leonti Bielski Date: Fri, 28 Jun 2013 12:23:36 +0200 Subject: [PATCH 032/441] #146 Explicitly check if element id is null or undefined --- src/restangular.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/restangular.js b/src/restangular.js index 862910e2..a7104e12 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -373,7 +373,7 @@ module.provider('Restangular', function() { if (!elem[__this.config.restangularFields.restangularCollection]) { var elemId = __this.config.getIdFromElem(elem); - if (elemId) { + if (!_.isUndefined(elemId) && !_.isNull(elemId)) { currUrl += "/" + elemId; } } From c4da4a59e3e209852717302e6e7d5a82d3a88f2c Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Fri, 28 Jun 2013 12:23:40 -0300 Subject: [PATCH 033/441] v1.0.4 --- bower.json | 2 +- dist/restangular.js | 4 ++-- dist/restangular.min.js | 4 ++-- dist/restangular.zip | Bin 41894 -> 41959 bytes package.json | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/bower.json b/bower.json index 484908c7..6ab19196 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "1.0.3", + "version": "1.0.4", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { diff --git a/dist/restangular.js b/dist/restangular.js index 22a88650..381a3077 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.3 - 2013-06-26 + * @version v1.0.4 - 2013-06-28 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT @@ -380,7 +380,7 @@ module.provider('Restangular', function() { if (!elem[__this.config.restangularFields.restangularCollection]) { var elemId = __this.config.getIdFromElem(elem); - if (elemId) { + if (!_.isUndefined(elemId) && !_.isNull(elemId)) { currUrl += "/" + elemId; } } diff --git a/dist/restangular.min.js b/dist/restangular.min.js index d795c1b8..31bbeb11 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.3 - 2013-06-26 + * @version v1.0.4 - 2013-06-28 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);request=f.fullRequestInterceptor(s,a,p,r,h||{},l||{});var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},request.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,request.params,b)[v]({}).then(t,u):H.resource(this,c,w,request.params,b)[v]().then(t,u):H.resource(this,c,w,request.params,b)[v](request.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",void 0,a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,b),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);request=f.fullRequestInterceptor(s,a,p,r,h||{},l||{});var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},request.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,request.params,b)[v]({}).then(t,u):H.resource(this,c,w,request.params,b)[v]().then(t,u):H.resource(this,c,w,request.params,b)[v](request.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",void 0,a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,b),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 923ae8a0acc5a281999271e0bd69b8137795cc6c..63d84b081c64fa9075c5e4468245f0da5b47bde3 100644 GIT binary patch delta 266 zcmZ2>oay;-Cf)#VW)?065O|YxXCkixFOYKTe5^ZfM>PY(j)_(Yd?pII3PuKo#<~V( zx<(e03u;zu4q&`ssjV2VmsuQ|my(*6nU|WPk(!g5>zSgdpr)n(mhmgi$$<$@UZ^HL z`GX4UW;g5A4qzL8C(B4*S7TtfKKWmD3Yrz03u+jJ<KsKuiU4Hkb703o`>9 nJNeln15`&(R$gqP0P+Uh5}-xmU_ZhLo|?(!i#6FK7J~!;zqMH# delta 199 zcmaEUoN3u{Cf)#VW)?065O89=HIY|=7f3nXs=m@Zxtf7t@<|= C6FsN^ diff --git a/package.json b/package.json index 6fd37978..fc295262 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "restangular", "description": "Restfull Resources service for AngularJS apps", - "version": "1.0.3", + "version": "1.0.4", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", "author": "Martin Gontovnikas ", From 1512dea27b3c21450340a52168aebdb75bf8d828 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Fri, 28 Jun 2013 19:06:23 -0300 Subject: [PATCH 034/441] Added FAQ question on how to get unrestangularized element Fixes #100 --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index 817dbba4..03a8089a 100644 --- a/README.md +++ b/README.md @@ -697,6 +697,18 @@ However, changes to that promise that you do from your HTML won't be seen in the It won't be stripped out anymore as I've ditched `$resource` :). Now you can happily put the port :). +#### How can I access the `unrestangularized` element as well as the `restangularized` one? + +In order to get this done, you need to use the `responseExtractor`. You need to set a property there that will point to the original response received. Also, you need to actually copy this response as that response is the one that's going to be `restangularized` later + +````javascript +RestangularProvider.setResponseExtractor(function(response) { + var newResponse = response; + newResponse.originalElement = angular.copy(response); + return newResponse; +}); +```` + #### Why does this depend on Lodash / Underscore? This is a very good question. I could've done the code so that I don't depend on Underscore nor Lodash, but I think both libraries make your life SO much easier. They have all of the "functional" stuff like map, reduce, filter, find, etc. From bbc7a382c883cd890edee7867f9ee14688510d12 Mon Sep 17 00:00:00 2001 From: Sam Pepose Date: Sun, 7 Jul 2013 11:09:16 -0500 Subject: [PATCH 035/441] Fixed implicit var declaration --- src/restangular.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/restangular.js b/src/restangular.js index a7104e12..1d92cc6a 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -1,3 +1,5 @@ +'use strict'; + (function(){ var module = angular.module('restangular', []); @@ -569,7 +571,7 @@ module.provider('Restangular', function() { var whatFetched = what || __this[config.restangularFields.route]; - var request = config.fullRequestInterceptor(null, operation, + var request = config.fullRequestInterceptor(null, operation, whatFetched, url, headers || {}, reqParams || {}); urlHandler.resource(this, $http, request.headers, request.params, what).getList().then(function(response) { @@ -608,7 +610,7 @@ module.provider('Restangular', function() { var fetchUrl = urlHandler.fetchUrl(this, what); var callObj = obj || stripRestangular(this); - request = config.fullRequestInterceptor(callObj, operation, route, fetchUrl, + var request = config.fullRequestInterceptor(callObj, operation, route, fetchUrl, headers || {}, resParams || {}); var okCallback = function(response) { From 307b2b7a8dde73620c1f63216d58e5856782d3f9 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Tue, 9 Jul 2013 14:55:42 -0300 Subject: [PATCH 036/441] Fixed bug on scoped Service configuration Fixes #160 --- dist/restangular.js | 4 ++-- dist/restangular.min.js | 4 ++-- dist/restangular.zip | Bin 41959 -> 41946 bytes src/restangular.js | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/dist/restangular.js b/dist/restangular.js index 381a3077..7c64f572 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.4 - 2013-06-28 + * @version v1.0.4 - 2013-07-09 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT @@ -724,7 +724,7 @@ module.provider('Restangular', function() { } - Configurer.init(service, globalConfiguration); + Configurer.init(service, config); service.copy = _.bind(copyRestangularizedElement, service); diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 31bbeb11..999c9aa9 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.4 - 2013-06-28 + * @version v1.0.4 - 2013-07-09 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);request=f.fullRequestInterceptor(s,a,p,r,h||{},l||{});var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},request.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,request.params,b)[v]({}).then(t,u):H.resource(this,c,w,request.params,b)[v]().then(t,u):H.resource(this,c,w,request.params,b)[v](request.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",void 0,a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,b),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);request=f.fullRequestInterceptor(s,a,p,r,h||{},l||{});var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},request.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,request.params,b)[v]({}).then(t,u):H.resource(this,c,w,request.params,b)[v]().then(t,u):H.resource(this,c,w,request.params,b)[v](request.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",void 0,a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 63d84b081c64fa9075c5e4468245f0da5b47bde3..3af213775d6a462d102c1a4021bbdba84aa2d93b 100644 GIT binary patch delta 156 zcmaEUoaxqaCf)#VW)?065I9`+aw4w+FOYJwW#innx|)Gu^+c;I7IR$#%Z)2`RB$Bc z=cQ$)Yg$j<=pi>*pqgXz?8<5;4v>1&jauoGWd9f&7GXG*aV?-!D2C{|J9RsEY@V>UJP;y0AR#AJpcdz delta 165 zcmcb0oay;-Cf)#VW)?065O|YxXCkixFOYKTe5^ZfM>PY(j)_)TEM~e!78_UWsF=Lb zR&4TxYOcvLRnnXLDyx||KuUin%ScZatSJU7+uTueOqDTdvj3tJ%s|P>Qi}~x&6^y) f*hB%Q?YbHR0|<+Qt%ngjHIr8_)?|}d3=#kUg2Xyy diff --git a/src/restangular.js b/src/restangular.js index 1d92cc6a..fa3a312c 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -719,7 +719,7 @@ module.provider('Restangular', function() { } - Configurer.init(service, globalConfiguration); + Configurer.init(service, config); service.copy = _.bind(copyRestangularizedElement, service); From 64bbecbde76936373dcdfaa9adb3be00639f4a35 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Tue, 9 Jul 2013 14:57:36 -0300 Subject: [PATCH 037/441] Implemented patch to receive element parameter Fixes #145 --- dist/restangular.js | 4 ++-- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 41946 -> 41944 bytes src/restangular.js | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/dist/restangular.js b/dist/restangular.js index 7c64f572..19db4748 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -686,8 +686,8 @@ module.provider('Restangular', function() { return _.bind(elemFunction, this)("options", undefined, params, undefined, headers); } - function patchFunction(params, headers) { - return _.bind(elemFunction, this)("patch", undefined, params, undefined, headers); + function patchFunction(elem, params, headers) { + return _.bind(elemFunction, this)("patch", undefined, params, elem, headers); } function customFunction(operation, path, params, headers, elem) { diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 999c9aa9..3aeb4130 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -5,4 +5,4 @@ * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);request=f.fullRequestInterceptor(s,a,p,r,h||{},l||{});var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},request.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,request.params,b)[v]({}).then(t,u):H.resource(this,c,w,request.params,b)[v]().then(t,u):H.resource(this,c,w,request.params,b)[v](request.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b){return _.bind(u,this)("patch",void 0,a,void 0,b)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);request=f.fullRequestInterceptor(s,a,p,r,h||{},l||{});var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},request.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,request.params,b)[v]({}).then(t,u):H.resource(this,c,w,request.params,b)[v]().then(t,u):H.resource(this,c,w,request.params,b)[v](request.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 3af213775d6a462d102c1a4021bbdba84aa2d93b..1a42342ce73891867f6979fdf4d376085aba0115 100644 GIT binary patch delta 198 zcmcb0oax4KCY}IqW)?065HKj8$fL+>Q2x^CBIjG)HPs9ZYc^U{6iwzW(3t!|mVL58 zk<8@pMbeWC3S=keDf3VEP347OP27VbV#Sd~kt; zh*CjfNpgmgPFa3tih_Yol1`#d^5)eGa+sJ5$|p-MHbk{?a`<8s1&|xyh5-!}2fGhW P)J$HzSd)!&F-QOaxwSxL delta 190 zcmca{oaxqaCY}IqW)?065I9^mkw=mDaM?>ITQ<&JtE(9pR&TVbD4NV( Date: Tue, 9 Jul 2013 15:07:02 -0300 Subject: [PATCH 038/441] Added parentLess configuration Fixes #154 --- dist/restangular.js | 18 ++++++++++++++++-- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 41944 -> 42774 bytes src/restangular.js | 18 ++++++++++++++++-- 4 files changed, 33 insertions(+), 5 deletions(-) diff --git a/dist/restangular.js b/dist/restangular.js index 19db4748..516f95e9 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -199,6 +199,21 @@ module.provider('Restangular', function() { }; + config.shouldSaveParent = config.shouldSaveParent || function() { + return true; + } + object.setParentless = function(values) { + if (_.isArray(values)) { + config.shouldSaveParent = function(route) { + return !_.contains(values, route); + } + } else if (_.isBoolean(values)) { + config.shouldSaveParent = function() { + return !values; + } + } + } + /** * This lets you set a suffix to every request. * @@ -428,8 +443,7 @@ module.provider('Restangular', function() { // RequestLess connection elem.one = _.bind(one, elem, elem); elem.all = _.bind(all, elem, elem); - - if (parent) { + if (parent && config.shouldSaveParent(route)) { var restangularFieldsForParent = _.union( _.values( _.pick(config.restangularFields, ['id', 'route', 'parentResource']) ), config.extraFields diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 3aeb4130..89bc9f8b 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -5,4 +5,4 @@ * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);request=f.fullRequestInterceptor(s,a,p,r,h||{},l||{});var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},request.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,request.params,b)[v]({}).then(t,u):H.resource(this,c,w,request.params,b)[v]().then(t,u):H.resource(this,c,w,request.params,b)[v](request.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);request=f.fullRequestInterceptor(s,a,p,r,h||{},l||{});var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},request.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,request.params,b)[v]({}).then(t,u):H.resource(this,c,w,request.params,b)[v]().then(t,u):H.resource(this,c,w,request.params,b)[v](request.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 1a42342ce73891867f6979fdf4d376085aba0115..9497c8c3a6380554d2fe453d286de38f9415f9fc 100644 GIT binary patch delta 737 zcmca{oN3xQCY}IqW)?065V%n>kw=m5M#W2~l01L8KeY@De`+^c3&>CIQ{d3a$S=)F z2~I3a4M;3X%_~u`RY=ayOUq2xD@K>8shQlbDLvU=n~SBSs5Eu*duy4=zN}oF5REyh z#gjj9s!oC`-&KO)b`(yiiSIasdmw42Ge$3TdTz$t9Wjc^Z=q z?4>7vP+^<=L6%)oFg0Wsg?zt;Sd_~a+cTd;0U zmTy;_yg-RXqW}^xYHGMbMg#0H&B-4l{w6r%l qY_YKdC^;g+h=D;IoK#^%K;2}S8cDGLZ&o&t5Hk?&1k&!yKs*3~5d~}j delta 178 zcmbPsj_Jm6CY}IqW)?065HKj8$fL+-Q2x^CBIjG)HPs9ZYpOR|3&>CYU@5VAiDJ9r z;~8g>SJW67uBdI!sN2oG`BzsU=jNm- u9|f5V$|r{|Gek3a@|0!93Lwi6`WP6*!482FHIsAdBquEwVB=g25(5CR0Xo?L diff --git a/src/restangular.js b/src/restangular.js index c164791d..2133a19a 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -194,6 +194,21 @@ module.provider('Restangular', function() { }; + config.shouldSaveParent = config.shouldSaveParent || function() { + return true; + } + object.setParentless = function(values) { + if (_.isArray(values)) { + config.shouldSaveParent = function(route) { + return !_.contains(values, route); + } + } else if (_.isBoolean(values)) { + config.shouldSaveParent = function() { + return !values; + } + } + } + /** * This lets you set a suffix to every request. * @@ -423,8 +438,7 @@ module.provider('Restangular', function() { // RequestLess connection elem.one = _.bind(one, elem, elem); elem.all = _.bind(all, elem, elem); - - if (parent) { + if (parent && config.shouldSaveParent(route)) { var restangularFieldsForParent = _.union( _.values( _.pick(config.restangularFields, ['id', 'route', 'parentResource']) ), config.extraFields From f42a21a2dd6a77d1177b55d10d0dfeb9ef99bb37 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Tue, 9 Jul 2013 15:09:49 -0300 Subject: [PATCH 039/441] Added documentation for parentless --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 03a8089a..a302b470 100644 --- a/README.md +++ b/README.md @@ -225,6 +225,14 @@ The base URL for all calls to your API. For example if your URL for fetching acc #### extraFields This are the fields that you want to save from your parent resources if you need to display them. By default this is an Empty Array which will suit most cases +#### parentless +With this property, you can set if you want Restangularized elements to have a parent or not. So, for example if you get an account and then get a nested list of buildings, you may want the buildings URL to be simple `/buildings/123` instead of `/accounts/123/buildings/123`. This configuration lets you do that. + +This method accepts 2 parameters: + +* Boolean: Specifies if all elements should be parentless or not +* Array: Specified the routes (types) of all elements that should be parentless. For example `['buildings']` + #### defaultHttpFields `$http` from AngularJS can receive a bunch of parameters like `cache`, `transformRequest` and so on. You can set all of those properties in the object sent on this setter so that they will be used in EVERY API call made by Restangular. This is very useful for caching for example. All properties that can be set can be checked here: http://docs.angularjs.org/api/ng.$http#Parameters From 10ec4a3a90dba92b2929e29fb5828be687da707f Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Tue, 9 Jul 2013 15:11:18 -0300 Subject: [PATCH 040/441] v1.0.5 --- CHANGELOG.md | 4 ++++ bower.json | 2 +- dist/restangular.js | 2 +- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 42774 -> 42774 bytes package.json | 2 +- 6 files changed, 8 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f3a918a..aa44fa7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +#1.0.5 +* Several bug fixes +* Added `parentless` configuration to ignore nested restful URLs + #1.0.2 * First final release * Added `one` and `all` to all collection methods diff --git a/bower.json b/bower.json index 6ab19196..2560c020 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "1.0.4", + "version": "1.0.5", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { diff --git a/dist/restangular.js b/dist/restangular.js index 516f95e9..0e39a2e7 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.4 - 2013-07-09 + * @version v1.0.5 - 2013-07-09 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 89bc9f8b..5e2e54c1 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.4 - 2013-07-09 + * @version v1.0.5 - 2013-07-09 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.zip b/dist/restangular.zip index 9497c8c3a6380554d2fe453d286de38f9415f9fc..0a7ec7835dee433469043864f39a58214d5a730f 100644 GIT binary patch delta 98 zcmbPsj%nICCY}IqW)?065J<0_$fL-SUis1~f=T-FMAKA8)5&M*wr&n!6IwtomvqY#nzswx~dh;d5 delta 98 zcmbPsj%nICCY}IqW)?065V%n>kw=l^M#W2~l01L8iKeNHCX>(9ZQUHe$W;p#R{2)& jdva1;CZoybGj;9iOgAbfhb}XO>zLfP%o3sQ{4#d{0%j=S diff --git a/package.json b/package.json index fc295262..1af357ff 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "restangular", "description": "Restfull Resources service for AngularJS apps", - "version": "1.0.4", + "version": "1.0.5", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", "author": "Martin Gontovnikas ", From eba9f7590d2f13436d1f6d6cdea6b32b1e308940 Mon Sep 17 00:00:00 2001 From: Justin Vencel Date: Wed, 10 Jul 2013 02:16:36 -0700 Subject: [PATCH 041/441] Fix code sample Second example of addElementTransformer under "Creating new Restangular Methods" was a copy /paste from above. --- README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a302b470..57d5f547 100644 --- a/README.md +++ b/README.md @@ -549,12 +549,11 @@ RestangularProvider.addElementTransformer('buildings', false, function(building) building.addRestangularMethod('evaluate', 'get', 'evaluate', undefined, {'myHeader': 'value'}); }); -RestangularProvider.addElementTransformer('users', true, function(users) { - // This will add a method called evaluate that will do a get to path evaluate with NO default - // query params and with some default header +RestangularProvider.addElementTransformer('users', true, function(user) { + // This will add a method called login that will do a POST to the path login // signature is (name, operation, path, params, headers, elementToPost) - users.addRestangularMethod('login', 'post', 'login'); + user.addRestangularMethod('login', 'post', 'login'); }); // Then, later in your code you can do the following: From bc2102ace0c9bcef3e8f1e33fe3e58fafa4a2857 Mon Sep 17 00:00:00 2001 From: Artyom Baranovskiy Date: Fri, 12 Jul 2013 09:50:17 +0300 Subject: [PATCH 042/441] Prevent url creator from duplicating slashes while building the url - The case is the following: BaseUrl is set to /someurl/ via RestangularProvider then all the built urls contain duplicated slashes like /someurl//Resource --- src/restangular.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/restangular.js b/src/restangular.js index 2133a19a..490b648a 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -20,7 +20,9 @@ module.provider('Restangular', function() { */ config.baseUrl = _.isUndefined(config.baseUrl) ? "" : config.baseUrl; object.setBaseUrl = function(newBaseUrl) { - config.baseUrl = newBaseUrl; + config.baseUrl = _.last(newBaseUrl) === "/" + ? _.initial(newBaseUrl).join("") + : newBaseUrl; } /** From f5cbeb8e7d4b3bd6f2bf6d745713f72d0585f97a Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Sat, 13 Jul 2013 02:13:41 -0300 Subject: [PATCH 043/441] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 57d5f547..e99293aa 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ You can download this by: #Dependencies -Restangular depends on Angular and (Underscore or Lodash). **angular-resource is no longer needed, now this uses `$http` instead of `$resource*`* +Restangular depends on Angular and (Underscore or Lodash). **angular-resource is no longer needed, now this uses `$http` instead of `$resource`** #Starter Guide From 116e4132c147e93dc2327ebfa8e1f98c18a19584 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Sat, 13 Jul 2013 02:21:22 -0300 Subject: [PATCH 044/441] v1.0.7 --- bower.json | 2 +- dist/restangular.js | 12 ++++++++---- dist/restangular.min.js | 4 ++-- dist/restangular.zip | Bin 42774 -> 42889 bytes package.json | 2 +- 5 files changed, 12 insertions(+), 8 deletions(-) diff --git a/bower.json b/bower.json index 2560c020..00f59a1f 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "1.0.5", + "version": "1.0.7", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { diff --git a/dist/restangular.js b/dist/restangular.js index 0e39a2e7..047c08ee 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,10 +1,12 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.5 - 2013-07-09 + * @version v1.0.7 - 2013-07-13 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ +'use strict'; + (function(){ var module = angular.module('restangular', []); @@ -25,7 +27,9 @@ module.provider('Restangular', function() { */ config.baseUrl = _.isUndefined(config.baseUrl) ? "" : config.baseUrl; object.setBaseUrl = function(newBaseUrl) { - config.baseUrl = newBaseUrl; + config.baseUrl = _.last(newBaseUrl) === "/" + ? _.initial(newBaseUrl).join("") + : newBaseUrl; } /** @@ -590,7 +594,7 @@ module.provider('Restangular', function() { var whatFetched = what || __this[config.restangularFields.route]; - var request = config.fullRequestInterceptor(null, operation, + var request = config.fullRequestInterceptor(null, operation, whatFetched, url, headers || {}, reqParams || {}); urlHandler.resource(this, $http, request.headers, request.params, what).getList().then(function(response) { @@ -629,7 +633,7 @@ module.provider('Restangular', function() { var fetchUrl = urlHandler.fetchUrl(this, what); var callObj = obj || stripRestangular(this); - request = config.fullRequestInterceptor(callObj, operation, route, fetchUrl, + var request = config.fullRequestInterceptor(callObj, operation, route, fetchUrl, headers || {}, resParams || {}); var okCallback = function(response) { diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 5e2e54c1..b03b0b1d 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.5 - 2013-07-09 + * @version v1.0.7 - 2013-07-13 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl=a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this);request=f.fullRequestInterceptor(s,a,p,r,h||{},l||{});var t=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},request.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,request.params,b)[v]({}).then(t,u):H.resource(this,c,w,request.params,b)[v]().then(t,u):H.resource(this,c,w,request.params,b)[v](request.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +"use strict";!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this),t=f.fullRequestInterceptor(s,a,p,r,h||{},l||{}),u=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},v=function(a){f.errorInterceptor(a),k.reject(a)},w=a,x=_.extend({},t.headers),y=f.isOverridenMethod(a);return y&&(w="post",x=_.extend(x,{"X-HTTP-Method-Override":a})),f.isSafe(a)?y?H.resource(this,c,x,t.params,b)[w]({}).then(u,v):H.resource(this,c,x,t.params,b)[w]().then(u,v):H.resource(this,c,x,t.params,b)[w](t.element).then(u,v),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 0a7ec7835dee433469043864f39a58214d5a730f..e19d9eae6d036ce120f16ac834ae4fec53879b63 100644 GIT binary patch delta 624 zcmbPsj;ZrJ6K{YwGYc032&@o#JCRp`4@fz2`L*p#sbgSBshemW&u6Znt6*ecXsl~s zu4`yK`DWb;KK0V#RE6S_qRiwHb!)E8{)|Sl5x4brv5c|p$Hd0t@JS#<`6vy;>7Qm{CaR|(-vCF{+N z^@2=lK<5Bm1$Aqprai(@iJEY?SZ$uvcuAH?r)2WIIZ~6`=8G`tlulkS|0+|N?d19M zlqSzyz$;g7o2XL(G$^&ABsDKZqqp-8s)Z11^LA# zO2}#}bgGpm_veUBmR=}aUuo~5SCm?uUs{x$s!@`WS*(++Qvo!qAh9Shw^%1hGrBw$ zXu76eNk(d(MyXDjrWFwyh*mBMv7kgRH77MUHLnDrar3=}r7X|}P1=w~i1Bn3u(@D`{ delta 486 zcmeA?&ou2E6K{YwGYc032&7lOoXD%d2c(=Ln4~ZNsbygJQ#;W*p3hW4SHZ}@&{)^N zT-U&IvSa;<&GC$e%$q;4e3F?gpdmTAmQQ#yi_(9a$*&~@CO^>U*en$v#Id;`JxH7v zWZL}J=H-Xf85j;tK3|uD&9razf=rurn=Z++TNkAkmZla@TA!SLQPGh z%vPx&zqmvRSx5Qg-i12#74{x_MXAO4rA5i98YLN-#X8A4<#3}45{nXZi*=GTqswA} zR%q&#WTfV4l<1UdS`n=cuO>0@8QWj=l&`mzM%m6JyCbKU$mPZLy WV91JtBM?ReOpaWx#pb>Y#0LOp(x>wP diff --git a/package.json b/package.json index 1af357ff..c54b2763 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "restangular", "description": "Restfull Resources service for AngularJS apps", - "version": "1.0.5", + "version": "1.0.7", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", "author": "Martin Gontovnikas ", From f088d5f7479e68afc94597dccfe4801f8500e6b9 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Sat, 13 Jul 2013 02:21:57 -0300 Subject: [PATCH 045/441] Changelog 1.0.7 --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index aa44fa7d..b64014a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +#1.0.7 +* `baseUrl` can now be set either with or without ending `/` and it'll work + #1.0.5 * Several bug fixes * Added `parentless` configuration to ignore nested restful URLs From 264ec99341968e743ffe60196c0725d7fdf9bf22 Mon Sep 17 00:00:00 2001 From: Justin Vencel Date: Sun, 14 Jul 2013 01:02:57 -0700 Subject: [PATCH 046/441] Documentation Updates Fixed a few variable naming issues in the config examples Cleaned up the wording as well. --- README.md | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index e99293aa..107d7a16 100644 --- a/README.md +++ b/README.md @@ -348,15 +348,17 @@ app.config(function(RestangularProvider) { return response.data; }); - RestangularProvider.addElementTransformer('accounts', false, function(elem) { - elem.accountName = 'Changed'; - return elem; + RestangularProvider.addElementTransformer('accounts', false, function(element) { + element.accountName = 'Changed'; + return element; }); RestangularProvider.setDefaultHttpFields({cache: true}); RestangularProvider.setMethodOverriders(["put", "patch"]); - // In this case we configure that the id of each element will be the _id field and we change the Restangular route. We leave the default value for parentResource + // In this case we are maping the id of each element to the _id field. + // We also change the Restangular route. + // The default value for parentResource remains the same. RestangularProvider.setRestangularFields({ id: "_id", route: "restangularRoute" @@ -366,15 +368,15 @@ app.config(function(RestangularProvider) { // Use Request interceptor RestangularProvider.setRequestInterceptor(function(element, operation, route, url) { - delete elem.name; - return elem; + delete element.name; + return element; }); - // Or full request interceptor, its powerfull brother + // ..or use the full request interceptor, setRequestInterceptor's more powerful brother! RestangularProvider.setFullRequestInterceptor(function(element, operation, route, url, headers, params) { - delete elem.name; + delete element.name; return { - element: elem, + element: element, params: _.extend(params, {single: true}), headers: headers }; From f9f420196e3a83207193aeee91400bfeb1fdeac9 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Mon, 15 Jul 2013 01:28:47 -0300 Subject: [PATCH 047/441] Update README.md Now addElementTransformer function returns transformed element. Fixes #170 --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 107d7a16..2b0f7f76 100644 --- a/README.md +++ b/README.md @@ -549,6 +549,8 @@ RestangularProvider.addElementTransformer('buildings', false, function(building) // signature is (name, operation, path, params, headers, elementToPost) building.addRestangularMethod('evaluate', 'get', 'evaluate', undefined, {'myHeader': 'value'}); + + return building; }); RestangularProvider.addElementTransformer('users', true, function(user) { @@ -556,6 +558,8 @@ RestangularProvider.addElementTransformer('users', true, function(user) { // signature is (name, operation, path, params, headers, elementToPost) user.addRestangularMethod('login', 'post', 'login'); + + return user; }); // Then, later in your code you can do the following: From 66037a145ac9ebf443a9164f3deb1097f1c618c7 Mon Sep 17 00:00:00 2001 From: David Date: Mon, 15 Jul 2013 16:25:24 -0700 Subject: [PATCH 048/441] fixes typo --- test/restangularSpec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/restangularSpec.js b/test/restangularSpec.js index e4d5187d..db04cbb4 100644 --- a/test/restangularSpec.js +++ b/test/restangularSpec.js @@ -102,7 +102,7 @@ describe("Restangular", function() { $httpBackend.flush(); }); - it("Custom GET methods sohuld work", function() { + it("Custom GET methods should work", function() { restangularAccounts.customGETLIST("messages").then(function(msgs) { expect(sanitizeRestangularAll(msgs)).toEqual(sanitizeRestangularAll(messages)); }); From 88bd08385bcb784803ba9461e1d9d1ce0e8c10d3 Mon Sep 17 00:00:00 2001 From: David Date: Mon, 15 Jul 2013 17:59:20 -0700 Subject: [PATCH 049/441] Adds unit test for Restangular.copy method. Documentation updates --- CONTRIBUTE.md | 11 +++++++++-- README.md | 2 +- dist/restangular.js | 2 +- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 42889 -> 42889 bytes test/restangularSpec.js | 18 ++++++++++++++++++ 6 files changed, 30 insertions(+), 5 deletions(-) diff --git a/CONTRIBUTE.md b/CONTRIBUTE.md index 1dc631dd..73a2b43f 100644 --- a/CONTRIBUTE.md +++ b/CONTRIBUTE.md @@ -1,10 +1,17 @@ In order to Contribute just git clone the repository and then run: +``` npm install grunt-cli --global npm install grunt -Be sure to have PhantomJS installed as Karma tests use it. Otherwise, in mac just run brew install phantomjs +``` -All changes must be done in src/restangular.jsand then after running gruntall changes will be submited to dist/ +Be sure to have PhantomJS installed as Karma tests use it. Otherwise, in mac just run + +``` +brew install phantomjs +``` + +All changes must be done in src/restangular.js and then after running grunt all changes will be submited to dist/ Please submit a Pull Request or create issues for anything you want :). diff --git a/README.md b/README.md index 2b0f7f76..850f010e 100644 --- a/README.md +++ b/README.md @@ -152,7 +152,7 @@ baseAccounts.getList().then(function (accounts) { // This is a regular JS object, we can change anything we want :) firstAccount.name = "Gonto" - //If we wanted to keep the original as it's we can copy it to a new element + //If we wanted to keep the original as it is, we can copy it to a new element var editFirstAccount = Restangular.copy(firstAccount); editFirstAccount.name = "New Name"; diff --git a/dist/restangular.js b/dist/restangular.js index 047c08ee..0e03096d 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.7 - 2013-07-13 + * @version v1.0.7 - 2013-07-15 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.min.js b/dist/restangular.min.js index b03b0b1d..2583df3e 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.7 - 2013-07-13 + * @version v1.0.7 - 2013-07-15 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.zip b/dist/restangular.zip index e19d9eae6d036ce120f16ac834ae4fec53879b63..684444dd45597f5e4fbe8f94e6688c566e486d47 100644 GIT binary patch delta 100 zcmeA?&(wLIi8sKTnT3l11U~e=pUA7g0i>J+bL`{MvR-G%aE@p6pn^VsijvQ7u?_=Xrr? ilTX!^F&b}ntZ!9k1}dF=a+v{K%VfsomI#GT%iRIphbA%r diff --git a/test/restangularSpec.js b/test/restangularSpec.js index db04cbb4..770922db 100644 --- a/test/restangularSpec.js +++ b/test/restangularSpec.js @@ -241,4 +241,22 @@ describe("Restangular", function() { }); }); + describe("COPY", function() { + it("should copy an object and 'this' should reference the copied object", function() { + var copiedAccount = Restangular.copy(accountsModel[0]); + var that; + + copiedAccount.user = "Copied string"; + expect(copiedAccount).not.toBe(accountsModel[0]); + + // create a spy for one of the methods to capture the value of 'this' + spyOn(copiedAccount, 'getRestangularUrl').andCallFake(function() { + that = this; + }); + + copiedAccount.getRestangularUrl(); // invoke the method we are spying on + expect(that).toBe(copiedAccount); + }); + }); + }); From 6307af71c0bf590d3381d4638f8413aa790b4aa0 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Tue, 16 Jul 2013 02:29:41 -0300 Subject: [PATCH 050/441] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 850f010e..36c364f6 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ You can download this by: #Dependencies -Restangular depends on Angular and (Underscore or Lodash). **angular-resource is no longer needed, now this uses `$http` instead of `$resource`** +Restangular depends on Angular and (Underscore or Lodash). **angular-resource is no longer needed since version 1.0.6, now this uses `$http` instead of `$resource`** #Starter Guide From 862b00fcd42fd5014abf9d354358f8fcd75b21e8 Mon Sep 17 00:00:00 2001 From: David Date: Mon, 15 Jul 2013 22:58:49 -0700 Subject: [PATCH 051/441] Adds unit test for getRestangularUrl() --- README.md | 2 +- test/restangularSpec.js | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 850f010e..68941c38 100644 --- a/README.md +++ b/README.md @@ -518,7 +518,7 @@ Sometimes, we have a lot of entities names with their ids and we just want to fe ````javascript -var restangualrSpaces = Restangular.one("accounts",123).one("buildings", 456).all("spaces"); +var restangularSpaces = Restangular.one("accounts",123).one("buildings", 456).all("spaces"); // This will do ONE get to /accounts/123/buildings/456/spaces restangularSpaces.getList() diff --git a/test/restangularSpec.js b/test/restangularSpec.js index 770922db..b011cd98 100644 --- a/test/restangularSpec.js +++ b/test/restangularSpec.js @@ -259,4 +259,11 @@ describe("Restangular", function() { }); }); + describe("getRestangularUrl", function() { + it("should return the generated URL when you chain Restangular methods together", function() { + var restangularSpaces = Restangular.one("accounts",123).one("buildings", 456).all("spaces"); + expect(restangularSpaces.getRestangularUrl()).toEqual("/accounts/123/buildings/456/spaces"); + }); + }); + }); From c65130ac50a813483da2cbbf6a2521491a732b6f Mon Sep 17 00:00:00 2001 From: David Date: Mon, 15 Jul 2013 23:00:20 -0700 Subject: [PATCH 052/441] Adds license to package.json --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index c54b2763..12a7a71c 100644 --- a/package.json +++ b/package.json @@ -41,5 +41,6 @@ }, "scripts": { "test": "grunt travis --verbose" - } + }, + "license": "MIT" } \ No newline at end of file From 69bbddd843b1021e24b06066b30097d4bf371445 Mon Sep 17 00:00:00 2001 From: Chris Boden Date: Mon, 15 Jul 2013 11:10:10 -0400 Subject: [PATCH 053/441] Fixed single element + trailing slash check elemId is returned as an empty string, not undefined or null The previous checks resulted in a false positive. --- dist/restangular.js | 2 +- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 42889 -> 42824 bytes src/restangular.js | 2 +- 4 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dist/restangular.js b/dist/restangular.js index 0e03096d..4f871da4 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -399,7 +399,7 @@ module.provider('Restangular', function() { if (!elem[__this.config.restangularFields.restangularCollection]) { var elemId = __this.config.getIdFromElem(elem); - if (!_.isUndefined(elemId) && !_.isNull(elemId)) { + if (elemId) { currUrl += "/" + elemId; } } diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 2583df3e..2aac3520 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -5,4 +5,4 @@ * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -"use strict";!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this),t=f.fullRequestInterceptor(s,a,p,r,h||{},l||{}),u=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},v=function(a){f.errorInterceptor(a),k.reject(a)},w=a,x=_.extend({},t.headers),y=f.isOverridenMethod(a);return y&&(w="post",x=_.extend(x,{"X-HTTP-Method-Override":a})),f.isSafe(a)?y?H.resource(this,c,x,t.params,b)[w]({}).then(u,v):H.resource(this,c,x,t.params,b)[w]().then(u,v):H.resource(this,c,x,t.params,b)[w](t.element).then(u,v),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +"use strict";!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this),t=f.fullRequestInterceptor(s,a,p,r,h||{},l||{}),u=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},v=function(a){f.errorInterceptor(a),k.reject(a)},w=a,x=_.extend({},t.headers),y=f.isOverridenMethod(a);return y&&(w="post",x=_.extend(x,{"X-HTTP-Method-Override":a})),f.isSafe(a)?y?H.resource(this,c,x,t.params,b)[w]({}).then(u,v):H.resource(this,c,x,t.params,b)[w]().then(u,v):H.resource(this,c,x,t.params,b)[w](t.element).then(u,v),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); diff --git a/dist/restangular.zip b/dist/restangular.zip index 684444dd45597f5e4fbe8f94e6688c566e486d47..806aca4451d5a63fd35f016eab90b642e7ff7eae 100644 GIT binary patch delta 155 zcmeA?&vfD(6HkCQGYc032z;rS$fL;nrQ*F)+F8!G_H_&l_8YBwY*|xtQgb~g3%ZF< zZZPE9ENHjU0jy}>#yZ!H>I@7UH=nPo6=6^=^ XToX{EIM`MgF?n+2axJ#XWgtEP`cX7t delta 237 zcmX?cj;ZrJ6HkCQGYc032z=<9$fL;nq3^wupsv~9lsX26l#NzBwpxnudYQ$cc`2!B znR%%x8mT#{xt=MS3TkQ!U>U#CoE)g& Date: Mon, 15 Jul 2013 11:17:39 -0400 Subject: [PATCH 054/441] Re-adjusted single element check --- dist/restangular.js | 2 +- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 42824 -> 42914 bytes src/restangular.js | 2 +- 4 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dist/restangular.js b/dist/restangular.js index 4f871da4..3a10e3ff 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -399,7 +399,7 @@ module.provider('Restangular', function() { if (!elem[__this.config.restangularFields.restangularCollection]) { var elemId = __this.config.getIdFromElem(elem); - if (elemId) { + if ("" !== elemId && !_.isUndefined(elemId) && !_.isNull(elemId)) { currUrl += "/" + elemId; } } diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 2aac3520..4f746fb3 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -5,4 +5,4 @@ * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -"use strict";!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);e&&(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this),t=f.fullRequestInterceptor(s,a,p,r,h||{},l||{}),u=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},v=function(a){f.errorInterceptor(a),k.reject(a)},w=a,x=_.extend({},t.headers),y=f.isOverridenMethod(a);return y&&(w="post",x=_.extend(x,{"X-HTTP-Method-Override":a})),f.isSafe(a)?y?H.resource(this,c,x,t.params,b)[w]({}).then(u,v):H.resource(this,c,x,t.params,b)[w]().then(u,v):H.resource(this,c,x,t.params,b)[w](t.element).then(u,v),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); +"use strict";!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);""===e||_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this),t=f.fullRequestInterceptor(s,a,p,r,h||{},l||{}),u=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},v=function(a){f.errorInterceptor(a),k.reject(a)},w=a,x=_.extend({},t.headers),y=f.isOverridenMethod(a);return y&&(w="post",x=_.extend(x,{"X-HTTP-Method-Override":a})),f.isSafe(a)?y?H.resource(this,c,x,t.params,b)[w]({}).then(u,v):H.resource(this,c,x,t.params,b)[w]().then(u,v):H.resource(this,c,x,t.params,b)[w](t.element).then(u,v),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 806aca4451d5a63fd35f016eab90b642e7ff7eae..893d665f7a7527e1376b7f1dbd10f4f87b0ad657 100644 GIT binary patch delta 262 zcmX?cj%m?(CY}IqW)?065KyU_$fL-sQuW>`>93_pX&nPY=|-y_TWcjH1w~t1h18tX zT+b8*H8lmrc)iTx(7cq?w9LHJ6b*=kCS1m^G$#itIJrSxcJcx#md$T$H#&fgo~3f) z%T;v-hO3)b)zylqD=FF9+NRdjpqZ!%5rLQl1KnIWnRCm&sAq5yI; k++d*L;$Z*4h?8}b*Vjpk1$eWvfrOZWa3_$yybQzx0M$BD9{>OV delta 160 zcmZ281a diff --git a/src/restangular.js b/src/restangular.js index c8ebaba9..56e849fd 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -392,7 +392,7 @@ module.provider('Restangular', function() { if (!elem[__this.config.restangularFields.restangularCollection]) { var elemId = __this.config.getIdFromElem(elem); - if (elemId) { + if ("" !== elemId && !_.isUndefined(elemId) && !_.isNull(elemId)) { currUrl += "/" + elemId; } } From f15d17adfac54bfc9bf0d6180baa04c89fcb0909 Mon Sep 17 00:00:00 2001 From: Chris Boden Date: Tue, 16 Jul 2013 10:18:10 -0400 Subject: [PATCH 055/441] grunt generation --- dist/restangular.js | 2 +- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 42914 -> 42914 bytes 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dist/restangular.js b/dist/restangular.js index 3a10e3ff..5c0ae759 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.7 - 2013-07-15 + * @version v1.0.7 - 2013-07-16 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 4f746fb3..6a0a6fe9 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.7 - 2013-07-15 + * @version v1.0.7 - 2013-07-16 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.zip b/dist/restangular.zip index 893d665f7a7527e1376b7f1dbd10f4f87b0ad657..67f636f79a47780254a53b6b53e5cd6c0500edd2 100644 GIT binary patch delta 111 zcmZ2 Date: Tue, 16 Jul 2013 14:24:11 -0700 Subject: [PATCH 056/441] Adds unit test for addElementTransformer - custom collection level method --- test/restangularSpec.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/test/restangularSpec.js b/test/restangularSpec.js index b011cd98..75be20a7 100644 --- a/test/restangularSpec.js +++ b/test/restangularSpec.js @@ -266,4 +266,24 @@ describe("Restangular", function() { }); }); + describe("addElementTransformer", function() { + it("should allow for a custom method to be placed at the collection level", function() { + var accountsPromise; + + Restangular.addElementTransformer('accounts', true, function(obj) { + obj.totalAmount = function() {}; + return obj; + }); + + accountsPromise = Restangular.all('accounts').getList(); + + accountsPromise.then(function(accounts) { + expect(typeof accounts.totalAmount).toEqual("function"); + }); + + $httpBackend.flush(); + }); + }); + + }); From 2ac94adae874141bbd241c0b577e2684e319e9b0 Mon Sep 17 00:00:00 2001 From: David Date: Tue, 16 Jul 2013 15:22:39 -0700 Subject: [PATCH 057/441] Adds unit test for addElementTransformer - custom element level method --- test/restangularSpec.js | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/test/restangularSpec.js b/test/restangularSpec.js index 75be20a7..90be7cac 100644 --- a/test/restangularSpec.js +++ b/test/restangularSpec.js @@ -269,10 +269,10 @@ describe("Restangular", function() { describe("addElementTransformer", function() { it("should allow for a custom method to be placed at the collection level", function() { var accountsPromise; - - Restangular.addElementTransformer('accounts', true, function(obj) { - obj.totalAmount = function() {}; - return obj; + + Restangular.addElementTransformer('accounts', true, function(collection) { + collection.totalAmount = function() {}; + return collection; }); accountsPromise = Restangular.all('accounts').getList(); @@ -283,6 +283,23 @@ describe("Restangular", function() { $httpBackend.flush(); }); + + it("should allow for a custom method to be placed at the element level", function() { + var accountPromise; + + Restangular.addElementTransformer('accounts', false, function(element) { + element.prettifyAmount = function() {}; + return element; + }); + + accountPromise = Restangular.one('accounts', 1).get(); + + accountPromise.then(function(account) { + expect(typeof account.prettifyAmount).toEqual("function"); + }); + + $httpBackend.flush(); + }); }); From 6b60a884cbee8996ed1a2b809179df530f208faf Mon Sep 17 00:00:00 2001 From: David Date: Tue, 16 Jul 2013 23:19:12 -0700 Subject: [PATCH 058/441] * Adds aliases extendsCollection and extendsModel for addElementTransformer * Adds documentation for new alias methods * Adds unit tests for new alias methods * Updates addElementTransformer unit test suite --- README.md | 50 ++++++++++++++++++++++++++++++++++-- dist/restangular.js | 8 ++++++ dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 42914 -> 43339 bytes src/restangular.js | 8 ++++++ test/restangularSpec.js | 55 +++++++++++++++++++++++++++++++++++++--- 6 files changed, 116 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 1d49b60d..9dae88b2 100644 --- a/README.md +++ b/README.md @@ -575,10 +575,56 @@ Restangular.one('building', 123).evaluate({myParam: 'param'}, {'myHeader': 'spec Restangular.all('users').login(); +```` +## Adding Custom Methods to Collections + +Create custom methods for your collection using Restangular.extendCollection(). This is an alias for: + +``` + Restangular.addElementTransformer(route, true, fn) +``` + +### Example: +``` + // create methods for your collection + Restangular.extendCollection('accounts', function(collection) { + collection.totalAmount = function() { + // implementation here + }; + + return collection; + }); + + var accountsPromise = Restangular.all('accounts').getList(); + + accountsPromise.then(function(accounts) { + accounts.totalAmount(); // invoke your custom collection method + }); +``` + +## Adding Custom Methods to Models + +Create custom methods for your models using Restangular.extendModel(). This is an alias for: + +``` + Restangular.addElementTransformer(route, false, fn) +``` + +### Example: +``` + Restangular.extendModel('accounts', function(model) { + model.prettifyAmount = function() {}; + return model; + }); + + var accountPromise = Restangular.one('accounts', 1).get(); + + accountPromise.then(function(account) { + account.prettifyAmount(); // invoke your custom model method + }); +``` -```` - # FAQ #### **How can I handle errors?** diff --git a/dist/restangular.js b/dist/restangular.js index 5c0ae759..75dca311 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -259,6 +259,14 @@ module.provider('Restangular', function() { }); } + object.extendCollection = function(route, fn) { + return object.addElementTransformer(route, true, fn); + }; + + object.extendModel = function(route, fn) { + return object.addElementTransformer(route, false, fn); + }; + config.transformElem = function(elem, isCollection, route, Restangular) { var typeTransformers = config.transformers[route]; var changedElem = elem; diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 6a0a6fe9..f3834acf 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -5,4 +5,4 @@ * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -"use strict";!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);""===e||_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this),t=f.fullRequestInterceptor(s,a,p,r,h||{},l||{}),u=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},v=function(a){f.errorInterceptor(a),k.reject(a)},w=a,x=_.extend({},t.headers),y=f.isOverridenMethod(a);return y&&(w="post",x=_.extend(x,{"X-HTTP-Method-Override":a})),f.isSafe(a)?y?H.resource(this,c,x,t.params,b)[w]({}).then(u,v):H.resource(this,c,x,t.params,b)[w]().then(u,v):H.resource(this,c,x,t.params,b)[w](t.element).then(u,v),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +"use strict";!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);""===e||_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this),t=f.fullRequestInterceptor(s,a,p,r,h||{},l||{}),u=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},v=function(a){f.errorInterceptor(a),k.reject(a)},w=a,x=_.extend({},t.headers),y=f.isOverridenMethod(a);return y&&(w="post",x=_.extend(x,{"X-HTTP-Method-Override":a})),f.isSafe(a)?y?H.resource(this,c,x,t.params,b)[w]({}).then(u,v):H.resource(this,c,x,t.params,b)[w]().then(u,v):H.resource(this,c,x,t.params,b)[w](t.element).then(u,v),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 67f636f79a47780254a53b6b53e5cd6c0500edd2..330a013a20df288c7eacd7346b59ae87e629023d 100644 GIT binary patch delta 403 zcmZ2V!X2BWldM@?lv+|+l&3IRzDHbFBS}Zm04P|i1Jed}8EzfyARUG} x$(x_{{E}n}-!=K+GDEO45TQ3&VY#sas>>J{#KD0LBc9ezE?%z5RFQUIr2b0FHSveE Date: Wed, 17 Jul 2013 09:07:33 +0200 Subject: [PATCH 059/441] Add collections to the unrestangularized element example --- README.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1d49b60d..35796c89 100644 --- a/README.md +++ b/README.md @@ -717,7 +717,14 @@ In order to get this done, you need to use the `responseExtractor`. You need to ````javascript RestangularProvider.setResponseExtractor(function(response) { var newResponse = response; - newResponse.originalElement = angular.copy(response); + if (angular.isArray(response)) { + angular.forEach(newResponse, function(value, key) { + newResponse[key].originalElement = angular.copy(value); + }); + } else { + newResponse.originalElement = angular.copy(response); + } + return newResponse; }); ```` From f05ef6b9b59f1d27ce84c05f83bf9d7b5bad4940 Mon Sep 17 00:00:00 2001 From: Crashthatch Date: Wed, 17 Jul 2013 12:25:26 +0100 Subject: [PATCH 060/441] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1d49b60d..00b66915 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Restangular.one('users').getList().then(function(users) { // This is a promise $scope.cars = $scope.user.getList('cars'); -// POST /users/123/sendMessage You've creat.ed your own method with the path & operation that you wanted +// POST /users/123/sendMessage You've created your own method with the path & operation that you wanted $scope.user.sendMessage(); // URL Building From 6860ff138bb18ab33f93b97d3786334cac0490b4 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 17 Jul 2013 09:22:36 -0700 Subject: [PATCH 061/441] Adds missing semicolons and code formatting so that it is consistent --- src/restangular.js | 105 +++++++++++++++++++++++---------------------- 1 file changed, 53 insertions(+), 52 deletions(-) diff --git a/src/restangular.js b/src/restangular.js index 63ceee50..6ee13cd6 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -1,6 +1,6 @@ 'use strict'; -(function(){ +(function() { var module = angular.module('restangular', []); @@ -14,7 +14,7 @@ module.provider('Restangular', function() { var safeMethods= ["get", "head", "options", "trace"]; config.isSafe = function(operation) { return _.contains(safeMethods, operation.toLowerCase()); - } + }; /** * This is the BaseURL to be used with Restangular */ @@ -23,15 +23,15 @@ module.provider('Restangular', function() { config.baseUrl = _.last(newBaseUrl) === "/" ? _.initial(newBaseUrl).join("") : newBaseUrl; - } + }; /** * Sets the extra fields to keep from the parents */ config.extraFields = config.extraFields || []; object.setExtraFields = function(newExtraFields) { - config.extraFields = newExtraFields; - } + config.extraFields = newExtraFields; + }; /** * Some default $http parameter to be used in EVERY call @@ -39,21 +39,21 @@ module.provider('Restangular', function() { config.defaultHttpFields = config.defaultHttpFields || {}; object.setDefaultHttpFields = function(values) { config.defaultHttpFields = values; - } + }; config.withHttpDefaults = function(obj) { return _.defaults(obj, config.defaultHttpFields); - } + }; config.defaultRequestParams = config.defaultRequestParams || {}; object.setDefaultRequestParams = function(values) { config.defaultRequestParams = values; - } + }; config.defaultHeaders = config.defaultHeaders || {}; object.setDefaultHeaders = function(headers) { config.defaultHeaders = headers; - } + }; /** * Method overriders will set which methods are sent via POST with an X-HTTP-Method-Override @@ -65,25 +65,26 @@ module.provider('Restangular', function() { overriders.push("remove"); } config.methodOverriders = overriders; - } + }; config.isOverridenMethod = function(method, values) { var search = values || config.methodOverriders; return !_.isUndefined(_.find(search, function(one) { return one.toLowerCase() === method.toLowerCase(); })); - } + }; /** * Sets the URL creator type. For now, only Path is created. In the future we'll have queryParams **/ config.urlCreator = config.urlCreator || "path"; object.setUrlCreator = function(name) { - if (!_.has(config.urlCreatorFactory, name)) { - throw new Error("URL Path selected isn't valid"); - } - config.urlCreator = name; - } + if (!_.has(config.urlCreatorFactory, name)) { + throw new Error("URL Path selected isn't valid"); + } + + config.urlCreator = name; + }; /** * You can set the restangular fields here. The 3 required fields for Restangular are: @@ -100,11 +101,11 @@ module.provider('Restangular', function() { route: "route", parentResource: "parentResource", restangularCollection: "restangularCollection" - } + }; object.setRestangularFields = function(resFields) { config.restangularFields = _.extend(config.restangularFields, resFields); - } + }; config.setIdToElem = function(elem, id) { var properties = config.restangularFields.id.split('.'); @@ -114,7 +115,7 @@ module.provider('Restangular', function() { idValue = idValue[prop]; }); idValue[_.last(properties)] = id; - } + }; config.getIdFromElem = function(elem) { var properties = config.restangularFields.id.split('.'); @@ -123,7 +124,7 @@ module.provider('Restangular', function() { idValue = idValue[prop]; }); return idValue; - } + }; /** * Sets the Response parser. This is used in case your response isn't directly the data. @@ -133,11 +134,12 @@ module.provider('Restangular', function() { * The ResponseExtractor is a function that receives the response and the method executed. */ config.responseExtractor = config.responseExtractor || function(response) { - return response; - } + return response; + }; + object.setResponseExtractor = function(extractor) { - config.responseExtractor = extractor; - } + config.responseExtractor = extractor; + }; object.setResponseInterceptor = object.setResponseExtractor; @@ -151,21 +153,21 @@ module.provider('Restangular', function() { headers: headers, params: params }; - } + }; object.setRequestInterceptor = function(interceptor) { - config.fullRequestInterceptor = function(elem, operation, path, url, headers, params) { - return { - headers: headers, - params: params, - element: interceptor(elem, operation, path, url) - } - }; - } + config.fullRequestInterceptor = function(elem, operation, path, url, headers, params) { + return { + headers: headers, + params: params, + element: interceptor(elem, operation, path, url) + } + }; + }; object.setFullRequestInterceptor = function(interceptor) { - config.fullRequestInterceptor = interceptor; - } + config.fullRequestInterceptor = interceptor; + }; @@ -173,7 +175,7 @@ module.provider('Restangular', function() { object.setErrorInterceptor = function(interceptor) { config.errorInterceptor = interceptor; - } + }; /** * This method is called after an element has been "Restangularized". @@ -183,11 +185,11 @@ module.provider('Restangular', function() { * */ config.onElemRestangularized = config.onElemRestangularized || function(elem) { - return elem; - } + return elem; + }; object.setOnElemRestangularized = function(post) { - config.onElemRestangularized = post; - } + config.onElemRestangularized = post; + }; /** * Depracated. Don't use this!! @@ -198,7 +200,7 @@ module.provider('Restangular', function() { config.shouldSaveParent = config.shouldSaveParent || function() { return true; - } + }; object.setParentless = function(values) { if (_.isArray(values)) { config.shouldSaveParent = function(route) { @@ -209,7 +211,7 @@ module.provider('Restangular', function() { return !values; } } - } + }; /** * This lets you set a suffix to every request. @@ -223,7 +225,7 @@ module.provider('Restangular', function() { config.suffix = _.isUndefined(config.suffix) ? null : config.suffix; object.setRequestSuffix = function(newSuffix) { config.suffix = newSuffix; - } + }; /** * Add element transformers for certain routes. @@ -250,7 +252,7 @@ module.provider('Restangular', function() { } return elem; }); - } + }; object.extendCollection = function(route, fn) { return object.addElementTransformer(route, true, fn); @@ -270,12 +272,12 @@ module.provider('Restangular', function() { } return config.onElemRestangularized(changedElem, isCollection, route, Restangular); - } + }; config.fullResponse = _.isUndefined(config.fullResponse) ? false : config.fullResponse; object.setFullResponse = function(full) { config.fullResponse = full; - } + }; @@ -291,7 +293,7 @@ module.provider('Restangular', function() { BaseCreator.prototype.setConfig = function(config) { this.config = config; - } + }; BaseCreator.prototype.parentsArray = function(current) { var parents = []; @@ -300,7 +302,7 @@ module.provider('Restangular', function() { current = current[this.config.restangularFields.parentResource]; } return parents.reverse(); - } + }; function RestangularResource($http, url, configurer) { var resource = {}; @@ -381,7 +383,7 @@ module.provider('Restangular', function() { params: params, headers: headers || {}}) }); - } + }; /** * This is the Path URL creator. It uses Path to show Hierarchy in the Rest API. @@ -407,7 +409,7 @@ module.provider('Restangular', function() { return currUrl; }, ''); - } + }; @@ -417,7 +419,7 @@ module.provider('Restangular', function() { baseUrl += "/" + what; } return baseUrl; - } + }; @@ -762,7 +764,6 @@ module.provider('Restangular', function() { return createServiceForConfiguration(globalConfiguration); - }]; } ); From 803067cc85bda1a5feea86cdc404624e28e87277 Mon Sep 17 00:00:00 2001 From: Paul Warelis Date: Tue, 23 Jul 2013 21:42:15 -0400 Subject: [PATCH 062/441] Fixing readme typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7c963f53..1b2f6ec0 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ $scope.user.sendMessage(); // URL Building // GET to /user/123/messages/123/from/123/unread -$scope.user.one('message', 123).one('from', 123).getList('unread') +$scope.user.one('messages', 123).one('from', 123).getList('unread') ```` From e19164bf190a55fd41cc5c9690eb6f556d76f9d2 Mon Sep 17 00:00:00 2001 From: Chris Boden Date: Thu, 25 Jul 2013 11:49:10 -0400 Subject: [PATCH 063/441] [feature] Add onBeforeElemRestangularized config option fixes #201 replaces #205 --- dist/restangular.js | 120 ++++++++++++++++++++++------------------ dist/restangular.min.js | 4 +- dist/restangular.zip | Bin 43339 -> 44042 bytes src/restangular.js | 15 ++++- 4 files changed, 81 insertions(+), 58 deletions(-) diff --git a/dist/restangular.js b/dist/restangular.js index 75dca311..66fa94ba 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,13 +1,13 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.7 - 2013-07-16 + * @version v1.0.7 - 2013-07-25 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ 'use strict'; -(function(){ +(function() { var module = angular.module('restangular', []); @@ -21,7 +21,7 @@ module.provider('Restangular', function() { var safeMethods= ["get", "head", "options", "trace"]; config.isSafe = function(operation) { return _.contains(safeMethods, operation.toLowerCase()); - } + }; /** * This is the BaseURL to be used with Restangular */ @@ -30,15 +30,15 @@ module.provider('Restangular', function() { config.baseUrl = _.last(newBaseUrl) === "/" ? _.initial(newBaseUrl).join("") : newBaseUrl; - } + }; /** * Sets the extra fields to keep from the parents */ config.extraFields = config.extraFields || []; object.setExtraFields = function(newExtraFields) { - config.extraFields = newExtraFields; - } + config.extraFields = newExtraFields; + }; /** * Some default $http parameter to be used in EVERY call @@ -46,21 +46,21 @@ module.provider('Restangular', function() { config.defaultHttpFields = config.defaultHttpFields || {}; object.setDefaultHttpFields = function(values) { config.defaultHttpFields = values; - } + }; config.withHttpDefaults = function(obj) { return _.defaults(obj, config.defaultHttpFields); - } + }; config.defaultRequestParams = config.defaultRequestParams || {}; object.setDefaultRequestParams = function(values) { config.defaultRequestParams = values; - } + }; config.defaultHeaders = config.defaultHeaders || {}; object.setDefaultHeaders = function(headers) { config.defaultHeaders = headers; - } + }; /** * Method overriders will set which methods are sent via POST with an X-HTTP-Method-Override @@ -72,25 +72,26 @@ module.provider('Restangular', function() { overriders.push("remove"); } config.methodOverriders = overriders; - } + }; config.isOverridenMethod = function(method, values) { var search = values || config.methodOverriders; return !_.isUndefined(_.find(search, function(one) { return one.toLowerCase() === method.toLowerCase(); })); - } + }; /** * Sets the URL creator type. For now, only Path is created. In the future we'll have queryParams **/ config.urlCreator = config.urlCreator || "path"; object.setUrlCreator = function(name) { - if (!_.has(config.urlCreatorFactory, name)) { - throw new Error("URL Path selected isn't valid"); - } - config.urlCreator = name; - } + if (!_.has(config.urlCreatorFactory, name)) { + throw new Error("URL Path selected isn't valid"); + } + + config.urlCreator = name; + }; /** * You can set the restangular fields here. The 3 required fields for Restangular are: @@ -107,11 +108,11 @@ module.provider('Restangular', function() { route: "route", parentResource: "parentResource", restangularCollection: "restangularCollection" - } + }; object.setRestangularFields = function(resFields) { config.restangularFields = _.extend(config.restangularFields, resFields); - } + }; config.setIdToElem = function(elem, id) { var properties = config.restangularFields.id.split('.'); @@ -121,7 +122,7 @@ module.provider('Restangular', function() { idValue = idValue[prop]; }); idValue[_.last(properties)] = id; - } + }; config.getIdFromElem = function(elem) { var properties = config.restangularFields.id.split('.'); @@ -130,7 +131,7 @@ module.provider('Restangular', function() { idValue = idValue[prop]; }); return idValue; - } + }; /** * Sets the Response parser. This is used in case your response isn't directly the data. @@ -140,11 +141,12 @@ module.provider('Restangular', function() { * The ResponseExtractor is a function that receives the response and the method executed. */ config.responseExtractor = config.responseExtractor || function(response) { - return response; - } + return response; + }; + object.setResponseExtractor = function(extractor) { - config.responseExtractor = extractor; - } + config.responseExtractor = extractor; + }; object.setResponseInterceptor = object.setResponseExtractor; @@ -158,21 +160,21 @@ module.provider('Restangular', function() { headers: headers, params: params }; - } + }; object.setRequestInterceptor = function(interceptor) { - config.fullRequestInterceptor = function(elem, operation, path, url, headers, params) { - return { - headers: headers, - params: params, - element: interceptor(elem, operation, path, url) - } - }; - } + config.fullRequestInterceptor = function(elem, operation, path, url, headers, params) { + return { + headers: headers, + params: params, + element: interceptor(elem, operation, path, url) + } + }; + }; object.setFullRequestInterceptor = function(interceptor) { - config.fullRequestInterceptor = interceptor; - } + config.fullRequestInterceptor = interceptor; + }; @@ -180,7 +182,14 @@ module.provider('Restangular', function() { object.setErrorInterceptor = function(interceptor) { config.errorInterceptor = interceptor; + }; + + config.onBeforeElemRestangularized = config.onBeforeElemRestangularized || function(elem) { + return elem; } + object.setOnBeforeElemRestangularized = function(post) { + config.onBeforeElemRestangularized = post; + }; /** * This method is called after an element has been "Restangularized". @@ -190,11 +199,11 @@ module.provider('Restangular', function() { * */ config.onElemRestangularized = config.onElemRestangularized || function(elem) { - return elem; - } + return elem; + }; object.setOnElemRestangularized = function(post) { - config.onElemRestangularized = post; - } + config.onElemRestangularized = post; + }; /** * Depracated. Don't use this!! @@ -205,7 +214,7 @@ module.provider('Restangular', function() { config.shouldSaveParent = config.shouldSaveParent || function() { return true; - } + }; object.setParentless = function(values) { if (_.isArray(values)) { config.shouldSaveParent = function(route) { @@ -216,7 +225,7 @@ module.provider('Restangular', function() { return !values; } } - } + }; /** * This lets you set a suffix to every request. @@ -230,7 +239,7 @@ module.provider('Restangular', function() { config.suffix = _.isUndefined(config.suffix) ? null : config.suffix; object.setRequestSuffix = function(newSuffix) { config.suffix = newSuffix; - } + }; /** * Add element transformers for certain routes. @@ -257,7 +266,7 @@ module.provider('Restangular', function() { } return elem; }); - } + }; object.extendCollection = function(route, fn) { return object.addElementTransformer(route, true, fn); @@ -277,12 +286,12 @@ module.provider('Restangular', function() { } return config.onElemRestangularized(changedElem, isCollection, route, Restangular); - } + }; config.fullResponse = _.isUndefined(config.fullResponse) ? false : config.fullResponse; object.setFullResponse = function(full) { config.fullResponse = full; - } + }; @@ -298,7 +307,7 @@ module.provider('Restangular', function() { BaseCreator.prototype.setConfig = function(config) { this.config = config; - } + }; BaseCreator.prototype.parentsArray = function(current) { var parents = []; @@ -307,7 +316,7 @@ module.provider('Restangular', function() { current = current[this.config.restangularFields.parentResource]; } return parents.reverse(); - } + }; function RestangularResource($http, url, configurer) { var resource = {}; @@ -388,7 +397,7 @@ module.provider('Restangular', function() { params: params, headers: headers || {}}) }); - } + }; /** * This is the Path URL creator. It uses Path to show Hierarchy in the Rest API. @@ -414,7 +423,7 @@ module.provider('Restangular', function() { return currUrl; }, ''); - } + }; @@ -424,7 +433,7 @@ module.provider('Restangular', function() { baseUrl += "/" + what; } return baseUrl; - } + }; @@ -546,7 +555,9 @@ module.provider('Restangular', function() { copiedElement, copiedElement[config.restangularFields.route]); } - function restangularizeElem(parent, elem, route) { + function restangularizeElem(parent, element, route) { + var elem = config.onBeforeElemRestangularized(element, false, route); + var localElem = restangularizeBase(parent, elem, route); localElem[config.restangularFields.restangularCollection] = false; localElem.get = _.bind(getFunction, localElem); @@ -563,7 +574,9 @@ module.provider('Restangular', function() { return config.transformElem(localElem, false, route, service); } - function restangularizeCollection(parent, elem, route) { + function restangularizeCollection(parent, element, route) { + var elem = config.onBeforeElemRestangularized(element, true, route); + var localElem = restangularizeBase(parent, elem, route); localElem[config.restangularFields.restangularCollection] = true; localElem.post = _.bind(postFunction, localElem, null); @@ -769,7 +782,6 @@ module.provider('Restangular', function() { return createServiceForConfiguration(globalConfiguration); - }]; } ); diff --git a/dist/restangular.min.js b/dist/restangular.min.js index f3834acf..b5bd8027 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.7 - 2013-07-16 + * @version v1.0.7 - 2013-07-25 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -"use strict";!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);""===e||_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this),t=f.fullRequestInterceptor(s,a,p,r,h||{},l||{}),u=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},v=function(a){f.errorInterceptor(a),k.reject(a)},w=a,x=_.extend({},t.headers),y=f.isOverridenMethod(a);return y&&(w="post",x=_.extend(x,{"X-HTTP-Method-Override":a})),f.isSafe(a)?y?H.resource(this,c,x,t.params,b)[w]({}).then(u,v):H.resource(this,c,x,t.params,b)[w]().then(u,v):H.resource(this,c,x,t.params,b)[w](t.element).then(u,v),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +"use strict";!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);""===e||_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this),t=f.fullRequestInterceptor(s,a,p,r,h||{},l||{}),u=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},v=function(a){f.errorInterceptor(a),k.reject(a)},w=a,x=_.extend({},t.headers),y=f.isOverridenMethod(a);return y&&(w="post",x=_.extend(x,{"X-HTTP-Method-Override":a})),f.isSafe(a)?y?H.resource(this,c,x,t.params,b)[w]({}).then(u,v):H.resource(this,c,x,t.params,b)[w]().then(u,v):H.resource(this,c,x,t.params,b)[w](t.element).then(u,v),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 330a013a20df288c7eacd7346b59ae87e629023d..04f5d2a4d83cf529b359526c4162d826ed416b0f 100644 GIT binary patch delta 1575 zcma)6OKcle6!qAS$C<*nwgHj~K5e}NcXB>h3G9KJfk6n2 zgxHqLssIPYs3Ql@ihnYpi_HSO6}sf?j-TB?G*ewf3jRE-H57oOPu%5T(8Gfmi!s)h zO#)nt`Qf>k23JD@lw(O}3n1_CwHR4I{h$_5@_U&$<`bQr_MX2zb;j{nQ+7B& z1eSVR;r-q#4gtTWzD;v&#jUCBcG463o1xezQsshKvQRP&H%QmW3Otwn z-Sfy4v04hNQ2Kucn9H8T;;Ub5h3oU(B0Y9m^2z;&k}lVwBs`cm$%(^8`A4DF%6RQD z40@%z7DnJgC0G}FbF=Cw+>oL;Te%VxCQ|kD(W#888=q3gk}4XQRC4M#c}y3ORVo-V z0`6k(`~Z24Qj^FUIGh@tHpZ2sDk5x(yf9s?qLz*3OI75JHN>ou-n5|tnlX!gJ#~EHjSb~9k$VY&KjF?u)P#B6>^zKksL;moQ9cwq=yQE z(7BE4S)e`I0*w@$Z!APLO1e&sc!==->L$)m31o~MnZ?H}sDE5x6|Lv_nu_&{#aqsg r2_7;{P+8L0RMkG_@a@tLxpB~3t{D6HI~TkFTsZ-K9|nEtWeWZamM9Ju delta 1225 zcma)+Ye-XJ7{_A>AA&5gjMq;>QuLt@l16^%Qv_Y8$k7M;AV_u2d)%~;=zMq&&+mQS|MP#Ib9m3c zk&VBWF_qioNg9dp>>d5y%Wy3Ja-SM}ajrKik@QA;i<@O@*TLB}fJ&*EG)uE&@P`>( za%Phe`93KPVipc#DQc7@kKw6KjhdcpkXjfgbZmLSLGNnj!AxQIf&) Date: Sat, 27 Jul 2013 18:25:52 -0300 Subject: [PATCH 064/441] Now when no element is returned, undefined is used. Fixes #196 --- src/restangular.js | 15 ++++++++++----- test/restangularSpec.js | 32 ++++++++++++++++++++++---------- 2 files changed, 32 insertions(+), 15 deletions(-) diff --git a/src/restangular.js b/src/restangular.js index 490b648a..b86532e8 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -631,13 +631,18 @@ module.provider('Restangular', function() { var okCallback = function(response) { var resData = response.data; - var elem = config.responseExtractor(resData, operation, route, fetchUrl) || resObj; - if (operation === "post" && !__this[config.restangularFields.restangularCollection]) { - resolvePromise(deferred, response, restangularizeElem(__this, elem, what)); + var elem = config.responseExtractor(resData, operation, route, fetchUrl); + if (elem) { + + if (operation === "post" && !__this[config.restangularFields.restangularCollection]) { + resolvePromise(deferred, response, restangularizeElem(__this, elem, what)); + } else { + resolvePromise(deferred, response, restangularizeElem(__this[config.restangularFields.parentResource], elem, __this[config.restangularFields.route])); + } + } else { - resolvePromise(deferred, response, restangularizeElem(__this[config.restangularFields.parentResource], elem, __this[config.restangularFields.route])); + resolvePromise(deferred, response, undefined); } - }; var errorCallback = function(response) { diff --git a/test/restangularSpec.js b/test/restangularSpec.js index e4d5187d..f71db635 100644 --- a/test/restangularSpec.js +++ b/test/restangularSpec.js @@ -130,22 +130,19 @@ describe("Restangular", function() { }); it("Doing a post and then other operation (delete) should call right URLs", function() { - restangularAccounts.getList().then(function(accounts) { - accounts[1].post('transactions', {id: 1, name: "Gonto"}).then(function(transaction) { - transaction.remove(); - $httpBackend.expectDELETE('/accounts/1/transactions/1').respond(201, ''); - }); - }); - + restangularAccounts.post(newAccount).then(function(added) { + added.remove(); + $httpBackend.expectDELETE('/accounts/44').respond(201, ''); + }); + $httpBackend.flush(); }); - it("Doing a post to a server that returns no element will return the parameter of that post", function() { + it("Doing a post to a server that returns no element will return undefined", function() { restangularAccounts.getList().then(function(accounts) { var newTransaction = {id: 1, name: "Gonto"}; accounts[1].post('transactions', newTransaction).then(function(transaction) { - expect(sanitizeRestangularOne(transaction)) - .toEqual(sanitizeRestangularOne(newTransaction)); + expect(transaction).toBeUndefined(); }); }); @@ -174,6 +171,21 @@ describe("Restangular", function() { $httpBackend.flush(); }); + + it("getList() should correctly handle params after customDELETE", function() { + $httpBackend.expectGET('/accounts?foo=1').respond(accountsModel); + restangularAccounts.getList({foo: 1}).then(function(){ + $httpBackend.expectDELETE('/accounts?id=1').respond(201, ''); + return restangularAccounts.customDELETE('', {id: 1}); + }).then(function() { + $httpBackend.expectGET('/accounts?foo=1').respond(accountsModel); + return restangularAccounts.getList({foo: 1}); + }).then(function(accounts) { + expect(sanitizeRestangularAll(accounts)).toEqual(sanitizeRestangularAll(accountsModel)); + }); + + $httpBackend.flush(); + }); }); describe("ONE", function() { From 2fa3d539bb3c74a22d13d10a8cbef4805d640b67 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Sat, 27 Jul 2013 18:44:06 -0300 Subject: [PATCH 065/441] Added cannonical id configuration Fixes #187 --- README.md | 4 ++++ src/restangular.js | 21 +++++++++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e99293aa..7c431378 100644 --- a/README.md +++ b/README.md @@ -335,6 +335,10 @@ You can set default Headers to be sent with every request. If all of your requests require to send some suffix to work, you can set it here. For example, if you need to send the format like `/users/123.json`you can add that `.json` to the suffix using the `setRequestSuffix`method +#### useCannonicalId + +You can set this to either `true` or `false`. By default it's false. If set to true, then the cannonical ID from the element will be used for URL creation (in DELETE, PUT, POST, etc.). What this means is that if you change the ID of the element and then you do a put, if you set this to true, it'll use the "old" ID which was received from the server. If set to false, it'll use the new ID assigned to the element. + ### How to configure them globally You can do this configurations in either the `config` or the `run` method. If your configurations don't need any other services, then I'd recommend you do them in the `config`. If your configurations depend on other services, you can configure them in the `run` using `Restangular` instead of `RestangularProvider` diff --git a/src/restangular.js b/src/restangular.js index b86532e8..8281f5ce 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -99,7 +99,8 @@ module.provider('Restangular', function() { id: "id", route: "route", parentResource: "parentResource", - restangularCollection: "restangularCollection" + restangularCollection: "restangularCollection", + cannonicalId: "__cannonicalId" } object.setRestangularFields = function(resFields) { config.restangularFields = @@ -125,6 +126,11 @@ module.provider('Restangular', function() { return idValue; } + config.useCannonicalId = _.isUndefined(config.useCannonicalId) ? false : config.useCannonicalId; + object.setUseCannonicalId = function(value) { + config.useCannonicalId = value; + } + /** * Sets the Response parser. This is used in case your response isn't directly the data. * For example if you have a response like {meta: {'meta'}, data: {name: 'Gonto'}} @@ -391,7 +397,13 @@ module.provider('Restangular', function() { var currUrl = acum + "/" + elem[__this.config.restangularFields.route]; if (!elem[__this.config.restangularFields.restangularCollection]) { - var elemId = __this.config.getIdFromElem(elem); + var elemId; + if (config.useCannonicalId) { + elemId = elem[config.restangularFields.cannonicalId]; + } else { + elemId = __this.config.getIdFromElem(elem); + } + if (!_.isUndefined(elemId) && !_.isNull(elemId)) { currUrl += "/" + elemId; } @@ -533,6 +545,11 @@ module.provider('Restangular', function() { function restangularizeElem(parent, elem, route) { var localElem = restangularizeBase(parent, elem, route); + + if (config.useCannonicalId) { + localElem[config.restangularFields.cannonicalId] = config.getIdFromElem(localElem) + } + localElem[config.restangularFields.restangularCollection] = false; localElem.get = _.bind(getFunction, localElem); localElem.getList = _.bind(fetchFunction, localElem); From 99b4dcdd687fad872b4f82d72ba9707895f70d9a Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Sat, 27 Jul 2013 18:55:37 -0300 Subject: [PATCH 066/441] Implemented default request params per method Fixes #165 --- README.md | 6 +++++- src/restangular.js | 41 ++++++++++++++++++++++++++--------------- 2 files changed, 31 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 7c431378..6a3462cf 100644 --- a/README.md +++ b/README.md @@ -321,7 +321,11 @@ You can now Override HTTP Methods. You can set here the array of methods to over #### defaultRequestParams -You can set default Query parameters to be sent with every request +You can set default Query parameters to be sent with every request and every method. + +Additionally, if you want to configure request params per method, you can use `requestParams` configuration similar to `$http`. For example `RestangularProvider.requestParams.get = {single: true}`. + +Supported method to configure are: remove, get, post, put, common (all) #### fullResponse diff --git a/src/restangular.js b/src/restangular.js index 8281f5ce..b5172802 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -45,10 +45,18 @@ module.provider('Restangular', function() { return _.defaults(obj, config.defaultHttpFields); } - config.defaultRequestParams = config.defaultRequestParams || {}; + config.defaultRequestParams = config.defaultRequestParams || { + get: {}, + post: {}, + put: {}, + remove: {}, + common: {} + }; object.setDefaultRequestParams = function(values) { - config.defaultRequestParams = values; + config.defaultRequestParams.common = values; } + + object.requestParams = config.defaultRequestParams; config.defaultHeaders = config.defaultHeaders || {}; object.setDefaultHeaders = function(headers) { @@ -300,11 +308,14 @@ module.provider('Restangular', function() { return parents.reverse(); } - function RestangularResource($http, url, configurer) { + function RestangularResource(config, $http, url, configurer) { var resource = {}; _.each(_.keys(configurer), function(key) { var value = configurer[key]; - + + // Add default parameters + value.params = _.extend({}, value.params, + config.defaultRequestParams[value.method.toLowerCase()]); // We don't want the ? if no params are there if (_.isEmpty(value.params)) { delete value.params; @@ -335,49 +346,49 @@ module.provider('Restangular', function() { BaseCreator.prototype.resource = function(current, $http, callHeaders, callParams, what) { - var params = _.defaults(callParams || {}, this.config.defaultRequestParams); + var params = _.defaults(callParams || {}, this.config.defaultRequestParams.common); var headers = _.defaults(callHeaders || {}, this.config.defaultHeaders); var url = this.base(current); url += what ? ("/" + what): ''; url += (this.config.suffix || ''); - return RestangularResource($http, url, { + return RestangularResource(this.config, $http, url, { getList: this.config.withHttpDefaults({method: 'GET', params: params, - headers: headers || {}}), + headers: headers}), get: this.config.withHttpDefaults({method: 'GET', params: params, - headers: headers || {}}), + headers: headers}), put: this.config.withHttpDefaults({method: 'PUT', params: params, - headers: headers || {}}), + headers: headers}), post: this.config.withHttpDefaults({method: 'POST', params: params, - headers: headers || {}}), + headers: headers}), remove: this.config.withHttpDefaults({method: 'DELETE', params: params, - headers: headers || {}}), + headers: headers}), head: this.config.withHttpDefaults({method: 'HEAD', params: params, - headers: headers || {}}), + headers: headers}), trace: this.config.withHttpDefaults({method: 'TRACE', params: params, - headers: headers || {}}), + headers: headers}), options: this.config.withHttpDefaults({method: 'OPTIONS', params: params, - headers: headers || {}}), + headers: headers}), patch: this.config.withHttpDefaults({method: 'PATCH', params: params, - headers: headers || {}}) + headers: headers}) }); } From 73a6d9bbf00b308371c0c2f315cc65430979d47a Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Sat, 27 Jul 2013 19:08:31 -0300 Subject: [PATCH 067/441] Restangular method parameters depend on safety of operation Fixes #171 --- README.md | 9 +++++++-- src/restangular.js | 14 +++++++++++--- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 6a3462cf..5cc8eebc 100644 --- a/README.md +++ b/README.md @@ -567,15 +567,20 @@ RestangularProvider.addElementTransformer('users', true, function(user) { // Then, later in your code you can do the following: //GET to /buildings/123/evaluate?myParam=param with headers myHeader: value -//Signature for this "custom created" methods is (params, headers, elem) + +//Signature for this "custom created" methods is (params, headers, elem) if it's a safe operation (GET, OPTIONS, etc.) +// If it's an unsafe operation (POST, PUT, etc.), signature is (elem, params, headers). + // If something is set to any of this variables, the default set in the method creation will be overrided // If nothing is set, then the defaults are sent Restangular.one('building', 123).evaluate({myParam: 'param'}); //GET to /buildings/123/evaluate?myParam=param with headers myHeader: specialHeaderCase + Restangular.one('building', 123).evaluate({myParam: 'param'}, {'myHeader': 'specialHeaderCase'}); -Restangular.all('users').login(); +// Here the body of the POST is going to be {key: value} as POST is an unsafe operation +Restangular.all('users').login({key: value}); diff --git a/src/restangular.js b/src/restangular.js index b5172802..6c9cfeec 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -649,11 +649,10 @@ module.provider('Restangular', function() { var __this = this; var deferred = $q.defer(); var resParams = params || {}; - var resObj = obj || this; var route = what || this[config.restangularFields.route]; var fetchUrl = urlHandler.fetchUrl(this, what); - var callObj = obj || stripRestangular(this); + var callObj = obj || (operation === 'remove' ? undefined : stripRestangular(this)); var request = config.fullRequestInterceptor(callObj, operation, route, fetchUrl, headers || {}, resParams || {}); @@ -746,7 +745,7 @@ module.provider('Restangular', function() { bindedFunction = _.bind(customFunction, this, operation, path); } - this[name] = function(params, headers, elem) { + var createdFunction = function(params, headers, elem) { var callParams = _.defaults({ params: params, headers: headers, @@ -757,7 +756,16 @@ module.provider('Restangular', function() { elem: defaultElem }); return bindedFunction(callParams.params, callParams.headers, callParams.elem); + }; + + if (config.isSafe(operation)) { + this[name] = createdFunction; + } else { + this[name] = function(elem, params, headers) { + return createdFunction(params, headers, elem); + } } + } function withConfigurationFunction(configurer) { From 1fd94b687228a4aa4f7bff5d674f51edcce15753 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Sat, 27 Jul 2013 19:12:55 -0300 Subject: [PATCH 068/441] v1.0.8 --- CHANGELOG.md | 7 +++ bower.json | 2 +- dist/restangular.js | 93 +++++++++++++++++++++++++++++----------- dist/restangular.min.js | 4 +- dist/restangular.zip | Bin 42889 -> 45108 bytes package.json | 2 +- 6 files changed, 78 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b64014a4..82b0af45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +#1.0.8 +* **BREAKING CHANGE**: Restangular methods created with `addRestangularMethod` will change its signature depending on the opreation. If the operation is safe (GET, OPTIONS, etc.), the signature is methodName(params, headers, elemForBody). If it's not safe (POST, PUT, etc.), the signature is methodName(elemForBody, params, headers). This is to facilitate using them as when it's not safe, you're usually going to set a body +* Now you can configure default request parameters per method and for everything as well +* Added the ability to use Cannonical IDs. They're used if you need to change Primary Key (ID) of the element (Really weird case). +* If response is null or undefined, the element sent in the request ISN'T used anymore. This is to have clarity of what's returned by the server and also to fix one bug. + + #1.0.7 * `baseUrl` can now be set either with or without ending `/` and it'll work diff --git a/bower.json b/bower.json index 00f59a1f..0b0d779b 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "1.0.7", + "version": "1.0.8", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { diff --git a/dist/restangular.js b/dist/restangular.js index 047c08ee..36f1b2c9 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.7 - 2013-07-13 + * @version v1.0.8 - 2013-07-27 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT @@ -52,10 +52,18 @@ module.provider('Restangular', function() { return _.defaults(obj, config.defaultHttpFields); } - config.defaultRequestParams = config.defaultRequestParams || {}; + config.defaultRequestParams = config.defaultRequestParams || { + get: {}, + post: {}, + put: {}, + remove: {}, + common: {} + }; object.setDefaultRequestParams = function(values) { - config.defaultRequestParams = values; + config.defaultRequestParams.common = values; } + + object.requestParams = config.defaultRequestParams; config.defaultHeaders = config.defaultHeaders || {}; object.setDefaultHeaders = function(headers) { @@ -106,7 +114,8 @@ module.provider('Restangular', function() { id: "id", route: "route", parentResource: "parentResource", - restangularCollection: "restangularCollection" + restangularCollection: "restangularCollection", + cannonicalId: "__cannonicalId" } object.setRestangularFields = function(resFields) { config.restangularFields = @@ -132,6 +141,11 @@ module.provider('Restangular', function() { return idValue; } + config.useCannonicalId = _.isUndefined(config.useCannonicalId) ? false : config.useCannonicalId; + object.setUseCannonicalId = function(value) { + config.useCannonicalId = value; + } + /** * Sets the Response parser. This is used in case your response isn't directly the data. * For example if you have a response like {meta: {'meta'}, data: {name: 'Gonto'}} @@ -301,11 +315,14 @@ module.provider('Restangular', function() { return parents.reverse(); } - function RestangularResource($http, url, configurer) { + function RestangularResource(config, $http, url, configurer) { var resource = {}; _.each(_.keys(configurer), function(key) { var value = configurer[key]; - + + // Add default parameters + value.params = _.extend({}, value.params, + config.defaultRequestParams[value.method.toLowerCase()]); // We don't want the ? if no params are there if (_.isEmpty(value.params)) { delete value.params; @@ -336,49 +353,49 @@ module.provider('Restangular', function() { BaseCreator.prototype.resource = function(current, $http, callHeaders, callParams, what) { - var params = _.defaults(callParams || {}, this.config.defaultRequestParams); + var params = _.defaults(callParams || {}, this.config.defaultRequestParams.common); var headers = _.defaults(callHeaders || {}, this.config.defaultHeaders); var url = this.base(current); url += what ? ("/" + what): ''; url += (this.config.suffix || ''); - return RestangularResource($http, url, { + return RestangularResource(this.config, $http, url, { getList: this.config.withHttpDefaults({method: 'GET', params: params, - headers: headers || {}}), + headers: headers}), get: this.config.withHttpDefaults({method: 'GET', params: params, - headers: headers || {}}), + headers: headers}), put: this.config.withHttpDefaults({method: 'PUT', params: params, - headers: headers || {}}), + headers: headers}), post: this.config.withHttpDefaults({method: 'POST', params: params, - headers: headers || {}}), + headers: headers}), remove: this.config.withHttpDefaults({method: 'DELETE', params: params, - headers: headers || {}}), + headers: headers}), head: this.config.withHttpDefaults({method: 'HEAD', params: params, - headers: headers || {}}), + headers: headers}), trace: this.config.withHttpDefaults({method: 'TRACE', params: params, - headers: headers || {}}), + headers: headers}), options: this.config.withHttpDefaults({method: 'OPTIONS', params: params, - headers: headers || {}}), + headers: headers}), patch: this.config.withHttpDefaults({method: 'PATCH', params: params, - headers: headers || {}}) + headers: headers}) }); } @@ -398,7 +415,13 @@ module.provider('Restangular', function() { var currUrl = acum + "/" + elem[__this.config.restangularFields.route]; if (!elem[__this.config.restangularFields.restangularCollection]) { - var elemId = __this.config.getIdFromElem(elem); + var elemId; + if (config.useCannonicalId) { + elemId = elem[config.restangularFields.cannonicalId]; + } else { + elemId = __this.config.getIdFromElem(elem); + } + if (!_.isUndefined(elemId) && !_.isNull(elemId)) { currUrl += "/" + elemId; } @@ -540,6 +563,11 @@ module.provider('Restangular', function() { function restangularizeElem(parent, elem, route) { var localElem = restangularizeBase(parent, elem, route); + + if (config.useCannonicalId) { + localElem[config.restangularFields.cannonicalId] = config.getIdFromElem(localElem) + } + localElem[config.restangularFields.restangularCollection] = false; localElem.get = _.bind(getFunction, localElem); localElem.getList = _.bind(fetchFunction, localElem); @@ -628,23 +656,27 @@ module.provider('Restangular', function() { var __this = this; var deferred = $q.defer(); var resParams = params || {}; - var resObj = obj || this; var route = what || this[config.restangularFields.route]; var fetchUrl = urlHandler.fetchUrl(this, what); - var callObj = obj || stripRestangular(this); + var callObj = obj || (operation === 'remove' ? undefined : stripRestangular(this)); var request = config.fullRequestInterceptor(callObj, operation, route, fetchUrl, headers || {}, resParams || {}); var okCallback = function(response) { var resData = response.data; - var elem = config.responseExtractor(resData, operation, route, fetchUrl) || resObj; - if (operation === "post" && !__this[config.restangularFields.restangularCollection]) { - resolvePromise(deferred, response, restangularizeElem(__this, elem, what)); + var elem = config.responseExtractor(resData, operation, route, fetchUrl); + if (elem) { + + if (operation === "post" && !__this[config.restangularFields.restangularCollection]) { + resolvePromise(deferred, response, restangularizeElem(__this, elem, what)); + } else { + resolvePromise(deferred, response, restangularizeElem(__this[config.restangularFields.parentResource], elem, __this[config.restangularFields.route])); + } + } else { - resolvePromise(deferred, response, restangularizeElem(__this[config.restangularFields.parentResource], elem, __this[config.restangularFields.route])); + resolvePromise(deferred, response, undefined); } - }; var errorCallback = function(response) { @@ -720,7 +752,7 @@ module.provider('Restangular', function() { bindedFunction = _.bind(customFunction, this, operation, path); } - this[name] = function(params, headers, elem) { + var createdFunction = function(params, headers, elem) { var callParams = _.defaults({ params: params, headers: headers, @@ -731,7 +763,16 @@ module.provider('Restangular', function() { elem: defaultElem }); return bindedFunction(callParams.params, callParams.headers, callParams.elem); + }; + + if (config.isSafe(operation)) { + this[name] = createdFunction; + } else { + this[name] = function(elem, params, headers) { + return createdFunction(params, headers, elem); + } } + } function withConfigurationFunction(configurer) { diff --git a/dist/restangular.min.js b/dist/restangular.min.js index b03b0b1d..8bfe36f0 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.7 - 2013-07-13 + * @version v1.0.8 - 2013-07-27 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -"use strict";!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this),t=f.fullRequestInterceptor(s,a,p,r,h||{},l||{}),u=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},v=function(a){f.errorInterceptor(a),k.reject(a)},w=a,x=_.extend({},t.headers),y=f.isOverridenMethod(a);return y&&(w="post",x=_.extend(x,{"X-HTTP-Method-Override":a})),f.isSafe(a)?y?H.resource(this,c,x,t.params,b)[w]({}).then(u,v):H.resource(this,c,x,t.params,b)[w]().then(u,v):H.resource(this,c,x,t.params,b)[w](t.element).then(u,v),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +"use strict";!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return f.useCannonicalId&&(d[f.restangularFields.cannonicalId]=f.getIdFromElem(d)),d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index e19d9eae6d036ce120f16ac834ae4fec53879b63..3b874361426ba9ca4054fe1fe1852c656fc3dfd0 100644 GIT binary patch delta 2558 zcma)8TW}Lq7;f6MX#)u@=`986HbB{h?KW+})`TSuD71h~D^_MGp=@@~CV^bq-K4Fy z>4j1qonavT9TA<8qFm$w5mw$D^+iUg-UDQ~THB))dU`+k5lSKLeT9(_^M`FY1*$Tv1Bod2~Gc(NF zSIw1Gz^kQu%ege2;;CUFoIvUv&A>OsCW8WxOdAbu?Rx38Qs+{4L?IfDMMI(x?v`AX zV_+bg-~a=?3TrWIvlSCXu;3}Rs%S@+1bElhwj^?C4CSF@A*>?GMTxPf913uG9B{;9 zUz00@-IfzkF&>IVY2rVmELAXRG}YvZE`~>poK94+vH=c_#!*zFajDXYg9i}@JT5MSt0gA*$7EUE zpBBM7f-#AU$M(iXkg`Ki5zYAE{;sMU&7DS5Cj0o?26s54cA%}&V2KAqDn1}7z|I}p zd;wDJcHp*5=<83JHTdF`{%vYMf!DM8zPsZ%-0e80?@zsSyfDeYUmLdS5eHqXi-6u% z2c6AE_||N)=4J>gcGkdDiy3;}G#a}liiZc@dP{aueekfq77j-n!09X@Y;c_KoZD9p zgS;6A-mvLptX#Xr|5BwB{>RdMoe`Q}FM}@*)UC)df(>7{RV|~#G2B|Ogi(Zn>xU}A z8EMS$w`sraPpyQMe0@C~8$^mgYESVzPi;^T>HZD4j}lQ_#!wVVlncCp8j@~s$|dmg z;YRJlK)V6{*i{L{2kfE=5i8UfJbbZwkp?3pRwxSjpuF1%PO%y4_ZLHlV1p|myPg6f zdnB|K>W>Z;QB)GV5o`dbh2%j$i`Hjk8_J$Iqq~7mNz%SMR18<`R(KqELA!hOOAD#K zO;nH&N7BwrN0a7;-k}=p(&(QCoqI(?F*dO>Q^PV4BO739)Vd;15DX1AI1*h0)1%dJ zG(qcyU7$>+3?K9i)xzNRRnQ|<6K6W@M)0&+wR3N+HR^cvb+C8lE>lo&mw`JIVjf^= z-pO`@!4D%-+x7)ABf)16#3GRuxXd)YhK4Y-#Cyn0sr>=&nM1*_aC2&-L4bv+by$7z zG#H%ksJT3k!0*t&}1eYw!Z zKLIX*8CxPkeD-sS_QN|}rY9&-erjlWHaNiasoik<)XSzMqo)GyY*`OGPS?V~>78)p z^zKqj4ec`u*VTvK`FMvd<-EAdSN{?3Q*au?QJ& zT4LDToXX7jIHBxIgu^uXpwT9tI3qJj1;rCeltS7B{9aNe=V!mMk(QwM{VGR}WnNxl z61Upa$DDTJqo(2_|M)oEKck1}Vh8yyPDXJt*r$YPk{Z^}unHf*UO3WS=D<)Rc!pyk ziE_H4IuFCJDj4SLsufmXW9%Rs93RKM7$$FqjYG@)W)mheZsdW;{F#-m2z`td*|ZKO z$tHMkopZp(^OiNkyugm+43o-{3gX`o!;V7V`Fi^(j&hiHkP&cX^NzsD^X%lPr;AgN z8cQf5N(UgaBdnSkQyfkIun+&V7%m<}*n2j?xSm7cx!LV$11d*A6-DDu1-0H!4-}dM z>HZ43gK*uNV?wouk2uzprdv&c|*(d!E&8F!}WL0VpnLSD=XE9-`sq?^>LU-02t zht&OojA%dO3Avt*SXyyLRfxuBSV0S2^cjlq{S1D*}2AFRFB>y<)! z?O+kuNEXDGtOXNIoKZ$ZVCNrhi^fEwCT5v2@mF*S`_Di8v6%RmCVJPxR=4}(-TS=X z_ujkr!M6U~4ZX$xtifp3Y0qlyZ%Y>3s=khy2j;GDIh~HnE%`>RUc3!I;P!O1xxH;r4%C5dz^M41uw(F&_w7ntmhnvXwa)w<&IOyDxia+hq3JTTedv`k zblYo$nJ&3Z;_#g*LtDPNGUPve##G9eCCzX;g2V3)3a04_g`k}V*wcLk5;3DP)BR07 zd^BWI+J`=?weramfpMJ1<0_S9paYMTJ5`)`>RrRsKK*pqu&X|qG0baRbyKucl zr@P()=~?!k2`azLdNJ5PPs4ljk7EJ&e!dA~;GcQCDL`gKUP_4q&Jd#%KPmA7M}$x& zB}Thg#4!@n6;O_zwd*0faKu0}S>@M-&-KdJ=UEKuUaeI=UG!D~mVX&?`96~@XR=um zg?Okb5b#&tY1AaJr*OQ)_zOKH=0c&b#B3LO9@z1cM23YoRKLMxS4k->_m`Nf%e^H= zztXQ(e`2MtmL)S2jEHkI)7seH*vbwEV5|Khz)w|GMS{fsUA(v7ak6B|(*cT&3&BW; z3h~l2T#p!!Jr(6+1WWoxsYr5A;P_xf;5mXPWm%I9q@vLxAh=dqOTv@conCRu;_E+D z!p)16a_g z5rYy)L}9HBD5_BsrC??CV6`e%ONsm7+ts`wizXm@$-OU4GiZ{&Gb+_bqQX4G@nVuh zQ}ETLM_p6R%|x1ROvIB?W4Y}l7}k(y>d9V8UCww)WcgBcESgk%o$JXo(_gVa3-*lf|qIk8tydd2*RK8eyQEv{G<`MFRfLK3JjkLxMGb1pz zUXO)gV!gXLm?eEXjSdmv-NM4VpNYc7(2D*25zL_8E|50d_uMeJywQPcXYKA^q0>2w WH*c4Gn1jr$3-)c=DzCny3I7Axu-AJ4 diff --git a/package.json b/package.json index c54b2763..e6cf5a68 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "restangular", "description": "Restfull Resources service for AngularJS apps", - "version": "1.0.7", + "version": "1.0.8", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", "author": "Martin Gontovnikas ", From e6f5bd4b0d0138a630d4908f6813f4221d1b35d1 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Sat, 27 Jul 2013 19:16:50 -0300 Subject: [PATCH 069/441] v1.0.8 merged --- dist/restangular.js | 20 +------------------- dist/restangular.min.js | 10 +--------- dist/restangular.zip | Bin 45108 -> 46261 bytes 3 files changed, 2 insertions(+), 28 deletions(-) diff --git a/dist/restangular.js b/dist/restangular.js index 0eddfad4..31da36b0 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,10 +1,6 @@ /** * Restfull Resources service for AngularJS apps -<<<<<<< HEAD * @version v1.0.8 - 2013-07-27 -======= - * @version v1.0.7 - 2013-07-25 ->>>>>>> 6491d11323d3f94ea78705ac7f5ff85eb5b66a82 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT @@ -64,15 +60,11 @@ module.provider('Restangular', function() { common: {} }; object.setDefaultRequestParams = function(values) { -<<<<<<< HEAD config.defaultRequestParams.common = values; } object.requestParams = config.defaultRequestParams; -======= - config.defaultRequestParams = values; - }; ->>>>>>> 6491d11323d3f94ea78705ac7f5ff85eb5b66a82 + config.defaultHeaders = config.defaultHeaders || {}; object.setDefaultHeaders = function(headers) { @@ -124,14 +116,9 @@ module.provider('Restangular', function() { id: "id", route: "route", parentResource: "parentResource", -<<<<<<< HEAD restangularCollection: "restangularCollection", cannonicalId: "__cannonicalId" - } -======= - restangularCollection: "restangularCollection" }; ->>>>>>> 6491d11323d3f94ea78705ac7f5ff85eb5b66a82 object.setRestangularFields = function(resFields) { config.restangularFields = _.extend(config.restangularFields, resFields); @@ -446,7 +433,6 @@ module.provider('Restangular', function() { var currUrl = acum + "/" + elem[__this.config.restangularFields.route]; if (!elem[__this.config.restangularFields.restangularCollection]) { -<<<<<<< HEAD var elemId; if (config.useCannonicalId) { elemId = elem[config.restangularFields.cannonicalId]; @@ -454,11 +440,7 @@ module.provider('Restangular', function() { elemId = __this.config.getIdFromElem(elem); } - if (!_.isUndefined(elemId) && !_.isNull(elemId)) { -======= - var elemId = __this.config.getIdFromElem(elem); if ("" !== elemId && !_.isUndefined(elemId) && !_.isNull(elemId)) { ->>>>>>> 6491d11323d3f94ea78705ac7f5ff85eb5b66a82 currUrl += "/" + elemId; } } diff --git a/dist/restangular.min.js b/dist/restangular.min.js index af9e5994..0ce865fb 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,16 +1,8 @@ /** * Restfull Resources service for AngularJS apps -<<<<<<< HEAD * @version v1.0.8 - 2013-07-27 -======= - * @version v1.0.7 - 2013-07-25 ->>>>>>> 6491d11323d3f94ea78705ac7f5ff85eb5b66a82 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -<<<<<<< HEAD -"use strict";!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=g(a,b,c);return f.useCannonicalId&&(d[f.restangularFields.cannonicalId]=f.getIdFromElem(d)),d[f.restangularFields.restangularCollection]=!1,d.get=_.bind(v,d),d.getList=_.bind(t,d),d.put=_.bind(x,d),d.post=_.bind(y,d),d.remove=_.bind(w,d),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),o(d),f.transformElem(d,!1,c,G)}function r(a,b,c){var d=g(a,b,c);return d[f.restangularFields.restangularCollection]=!0,d.post=_.bind(y,d,null),d.head=_.bind(z,d),d.trace=_.bind(A,d),d.putElement=_.bind(s,d),d.options=_.bind(B,d),d.patch=_.bind(C,d),d.getList=_.bind(t,d,null),o(d),f.transformElem(d,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); -======= -"use strict";!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];_.isEmpty(g.params)&&delete g.params,e[f]=b.isSafe(g.method)?function(){return a(_.extend(g,{url:c}))}:function(b){return a(_.extend(g,{url:c,data:b}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{},a.setDefaultRequestParams=function(a){b.defaultRequestParams=a},b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h||{}}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h||{}}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h||{}}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h||{}}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h||{}}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h||{}}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h||{}}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h||{}})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var b=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,c){var d=a+"/"+c[b.config.restangularFields.route];if(!c[b.config.restangularFields.restangularCollection]){var e=b.config.getIdFromElem(c);""===e||_.isUndefined(e)||_.isNull(e)||(d+="/"+e)}return d},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=g||this,p=b||this[f.restangularFields.route],r=H.fetchUrl(this,b),s=g||n(this),t=f.fullRequestInterceptor(s,a,p,r,h||{},l||{}),u=function(c){var d=c.data,e=f.responseExtractor(d,a,p,r)||o;"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b))},v=function(a){f.errorInterceptor(a),k.reject(a)},w=a,x=_.extend({},t.headers),y=f.isOverridenMethod(a);return y&&(w="post",x=_.extend(x,{"X-HTTP-Method-Override":a})),f.isSafe(a)?y?H.resource(this,c,x,t.params,b)[w]({}).then(u,v):H.resource(this,c,x,t.params,b)[w]().then(u,v):H.resource(this,c,x,t.params,b)[w](t.element).then(u,v),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,f){var g;g="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c),this[a]=function(a,b,c){var h=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:f});return g(h.params,h.headers,h.elem)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); ->>>>>>> 6491d11323d3f94ea78705ac7f5ff85eb5b66a82 +"use strict";!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),""===f||_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return f.useCannonicalId&&(e[f.restangularFields.cannonicalId]=f.getIdFromElem(e)),e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 3b874361426ba9ca4054fe1fe1852c656fc3dfd0..742e204b572c21843d0480c1003f0ebd0d9596bd 100644 GIT binary patch delta 1949 zcma)7Z)h837|);fF1@Cgw25tE)ASm;nrzoJRk6c(bWJE|bt*bmTrJx*dDC@V@51G> z&aG1Sp{)2}wtEKEiVn7Z5GHK%Rqzk1^|K0sU!{on2Vu~GZi0$#s8*nq+6xs>x=Co$GD^SDmTJ(aml0<+Iyeah2CU_x4gX~l6 z?BIyn5FU&zZ=4Gm1YhTmwhsapy6zG4d02}QQ`mjzjDggAR#Oy|GbS`ukc2{6rOUXk zl?@~c1r_GmaE~^2$_z=$`TU@QCXs3!(Pgz{3Y|o{9ct)hnvh6yFqDjt3W8PPu$D*4 zuH>n`kQZd7w1u4*U+k*G{rh=q_Ah3Gpo*(ifkfn5l*hSlm3Y#H? z^;San;kfitO=B!3bV!nbOnpz~g|03E&JV1S5UgZa%S0t(-iQ4xM0gIabh8*|4+h+( z8Sutn8~7)idhOFECcS`4hOCa46O}Q>FGq zWm&$J>CVW}1Psl#)4z&8IL{};2ON&!19)oog4Z6se-=XaviZ`(_VUR~ondQacjzDA zU-;5BBPX}dj8vVNF)^1orz4}RtAf1CsEmmnDKqR<(I%p!v1g8YI&UUPub9Itm#;9M zSWJ?n!t^vAefv+QyO8`Z+pN5Vh@|njEau_mtL<(yQUDnR;P!9>ynD5gMG5mg#S$}; zSq3G?ks%#Vj!mff_-PTDZwd0uM5&4z7FsMp&1J;%0}*_jb#a@#mz?{X>wRsl$>T9!TZ-b(*J7^IUU;| zbD6H3=Y}OI(}3buVWL`A6k^OSLbmHLogyunm%(nkv`2vl^Kq(hr!%N@v9ox*x_pas rH7!BuM(?(7D130^5rKSGH|~nV(Lz7D_T$(boSO|p^roNr858hdo}ieI delta 1256 zcma)+Ye-XJ9L9I%E^cne^vtd4Mq6oav^H&omJD+`x)^B@g+(phR+@7gbJ`8+Ls@=F ztB1mgGJ=r&Ff?9;l9C{TAiMZklKNOteW-{Es&m<;q@V-maNghfU!Ldx9^UEK;;ENn zRdZvGL@DB~c>J=;OvmHj-9I|dKFsSAiSqhx)i@~9Ng2dgELDTnF))=$NiydU#e>rh z4jRxPoy8f60)yM~ppltyuz|*)T0{2AoWp9U7gXZmWy!R-vE?@hbC^kKx&f$Se zuSTNqI#-u8F+qwlp^hmc^O}mR3nQJ2XW9a?Ub`U1rQHhX^tx2Co40mvxdy}f<>?OO ziT*2vh@%89y$bJ2Ht<1-V*M3^0!@ZmBs>aiEYV=rRfszV4eT|mulOYRXmFvTv$cbKlHhUuBL8vDQ-a}5G+s9FYcl8QWU#Q= zNG4kzNVpeFwlw0yeg&!Z%B*npm-GMR-S(Yl=dB{qyp=@zFQ~95&XDBQNilgdG$JDd ziElFL5lgGB4bx*QC_nBei*PWZ#+R`Iso!d~aYPH3yXcI|Txs*$j|5^auf44!y1-4s{DO(i-!%r&&G6!WQ;%*v{4nbsr8#yF9@_m&Fh1O>+Tn+~%{^L<6y&Xvp-t z*$UQL@aLodt%qY75Q+l=E!fXHAbWaeN|` hOO7Nsr<^A4l*;}QB9V?i!O{ Date: Sat, 27 Jul 2013 19:18:39 -0300 Subject: [PATCH 070/441] v1.0.9 --- CHANGELOG.md | 5 ++++- bower.json | 2 +- dist/restangular.js | 2 +- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 46261 -> 46261 bytes package.json | 2 +- 6 files changed, 8 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82b0af45..9d0eeab4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,11 @@ -#1.0.8 +#1.0.9 * **BREAKING CHANGE**: Restangular methods created with `addRestangularMethod` will change its signature depending on the opreation. If the operation is safe (GET, OPTIONS, etc.), the signature is methodName(params, headers, elemForBody). If it's not safe (POST, PUT, etc.), the signature is methodName(elemForBody, params, headers). This is to facilitate using them as when it's not safe, you're usually going to set a body * Now you can configure default request parameters per method and for everything as well * Added the ability to use Cannonical IDs. They're used if you need to change Primary Key (ID) of the element (Really weird case). * If response is null or undefined, the element sent in the request ISN'T used anymore. This is to have clarity of what's returned by the server and also to fix one bug. +* Added tests +* Fixed bug with ID when it was an empty string +* Added missing ';'. #1.0.7 diff --git a/bower.json b/bower.json index 0b0d779b..d4f52877 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "1.0.8", + "version": "1.0.9", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { diff --git a/dist/restangular.js b/dist/restangular.js index 31da36b0..2cf19a88 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.8 - 2013-07-27 + * @version v1.0.9 - 2013-07-27 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 0ce865fb..a10036a5 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,6 +1,6 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.8 - 2013-07-27 + * @version v1.0.9 - 2013-07-27 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT diff --git a/dist/restangular.zip b/dist/restangular.zip index 742e204b572c21843d0480c1003f0ebd0d9596bd..51b465023815da69f20856adc2a94b2d74521593 100644 GIT binary patch delta 94 zcmdn`l4$lT=6Z4>nrm2jU8)u(v2a8-|6<9Pmrz4Zm fa^mc*o4Y&HwHS3Lf8J~aS3X&HizPy3-WGQNC43|c delta 94 zcmdn`l4$g)mYw_xdrm2h;8)u(v2a9~?;@CMkrz4Zm fV&d$ro4Y&HwHSpaf8J~aS3X&HizPy3-WGQN5Vj-D diff --git a/package.json b/package.json index 202fd53e..8fd59232 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "restangular", "description": "Restfull Resources service for AngularJS apps", - "version": "1.0.8", + "version": "1.0.9", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", "author": "Martin Gontovnikas ", From 154e84fc2305a2da28956f24f9333c6f356cb5d0 Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Sun, 28 Jul 2013 23:50:21 -0300 Subject: [PATCH 071/441] Added Twitter button --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2cac77d2..923846af 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,9 @@ #Restangular [![Build Status](https://travis-ci.org/mgonto/restangular.png)](https://travis-ci.org/mgonto/restangular) - + + + Restangular is an AngularJS service that will help you get, delete and update Restfull Resources with very few lines in the Client side. This service is a perfect fit for any WebApp that uses Restfull Resources as the API for your application. From 42eea35628a45b81d2294583a9a935bd474e646f Mon Sep 17 00:00:00 2001 From: Massimo Cetra Date: Mon, 29 Jul 2013 13:00:17 +0200 Subject: [PATCH 072/441] errorInterceptor does not intercept very well. Let the hook prevent the following actions. Setting an errorInterceptor function does not prevent the normal execution of the flow. Basically there is no way to prevent the data to reach the normal hooks. With this patch, which is backward compatible and should not introduce any regression, when tie errorInterceptor returns false (instead of the traditional response) the response does not reach the following hooks. As an example, if the API returns a 403 Unauthorized response, i cannot have a single hook to redirect the user to the login page. With this patch i could intercept every call and prevent the normal flow execution. --- src/restangular.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/restangular.js b/src/restangular.js index 8803a7df..fa75c474 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -660,8 +660,9 @@ module.provider('Restangular', function() { resolvePromise(deferred, response, restangularizeCollection(null, processedData, __this[config.restangularFields.route])); } }, function error(response) { - config.errorInterceptor(response); - deferred.reject(response); + if ( config.errorInterceptor(response) !== false ) { + deferred.reject(response); + } }); return restangularizePromise(deferred.promise, true); @@ -695,8 +696,9 @@ module.provider('Restangular', function() { }; var errorCallback = function(response) { - config.errorInterceptor(response); - deferred.reject(response); + if ( config.errorInterceptor(response) !== false ) { + deferred.reject(response); + } }; // Overring HTTP Method var callOperation = operation; From 03181528f764912b84e6a3502461c4e0d3dbbdff Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Mon, 29 Jul 2013 18:56:54 -0300 Subject: [PATCH 073/441] Update bower.json Updated Lodash version --- bower.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bower.json b/bower.json index d4f52877..7f1affd2 100644 --- a/bower.json +++ b/bower.json @@ -8,7 +8,7 @@ "url": "git://github.com/mgonto/restangular.git" }, "dependencies": { - "lodash": "~1.2.0", + "lodash": "~1.3.0", "angular": "*" }, "ignore": [ @@ -16,4 +16,4 @@ "components", "lib" ] -} \ No newline at end of file +} From 230f581d726bdbc9f2456becfc2278fa9eb9813b Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Tue, 30 Jul 2013 15:53:33 -0300 Subject: [PATCH 074/441] Removing strict mode It's causing issues in Safari 6 due to some bug on how they interpret Strict Mode :D. Fixes #212 --- bower.json | 4 +- dist/dependencies/lodash.js | 1232 +++++++++++++++++++++++------------ dist/restangular.js | 4 +- dist/restangular.min.js | 4 +- dist/restangular.zip | Bin 46261 -> 46235 bytes package.json | 2 +- src/restangular.js | 2 - 7 files changed, 810 insertions(+), 438 deletions(-) diff --git a/bower.json b/bower.json index 7f1affd2..4c874d65 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "1.0.9", + "version": "1.0.10", "main": "./dist/restangular.min.js", "description": "Restfull Resources service for AngularJS apps", "repository": { @@ -16,4 +16,4 @@ "components", "lib" ] -} +} \ No newline at end of file diff --git a/dist/dependencies/lodash.js b/dist/dependencies/lodash.js index 65069f0f..088c15b9 100644 --- a/dist/dependencies/lodash.js +++ b/dist/dependencies/lodash.js @@ -1,6 +1,6 @@ /** * @license - * Lo-Dash 1.2.1 + * Lo-Dash 1.3.1 * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.4.4 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud Inc. @@ -11,17 +11,9 @@ /** Used as a safe reference for `undefined` in pre ES5 environments */ var undefined; - /** Detect free variable `exports` */ - var freeExports = typeof exports == 'object' && exports; - - /** Detect free variable `module` */ - var freeModule = typeof module == 'object' && module && module.exports == freeExports && module; - - /** Detect free variable `global`, from Node.js or Browserified code, and use it as `window` */ - var freeGlobal = typeof global == 'object' && global; - if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { - window = freeGlobal; - } + /** Used to pool arrays and objects used internally */ + var arrayPool = [], + objectPool = []; /** Used to generate unique IDs */ var idCounter = 0; @@ -33,7 +25,10 @@ var keyPrefix = +new Date + ''; /** Used as the size when optimizations are enabled for large arrays */ - var largeArraySize = 200; + var largeArraySize = 75; + + /** Used as the max size of the `arrayPool` and `objectPool` */ + var maxPoolSize = 40; /** Used to match empty string literals in compiled template source */ var reEmptyStringLeading = /\b__p \+= '';/g, @@ -55,6 +50,9 @@ /** Used to match "interpolate" template delimiters */ var reInterpolate = /<%=([\s\S]+?)%>/g; + /** Used to detect functions containing a `this` reference */ + var reThis = (reThis = /\bthis\b/) && reThis.test(runInContext) && reThis; + /** Used to detect and test whitespace */ var whitespace = ( // whitespace @@ -81,9 +79,9 @@ /** Used to assign default `context` object properties */ var contextProps = [ - 'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object', 'RegExp', - 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN', 'parseInt', - 'setImmediate', 'setTimeout' + 'Array', 'Boolean', 'Date', 'Error', 'Function', 'Math', 'Number', 'Object', + 'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN', + 'parseInt', 'setImmediate', 'setTimeout' ]; /** Used to fix the JScript [[DontEnum]] bug */ @@ -100,6 +98,7 @@ arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', + errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', @@ -135,6 +134,305 @@ '\u2029': 'u2029' }; + /** Detect free variable `exports` */ + var freeExports = objectTypes[typeof exports] && exports; + + /** Detect free variable `module` */ + var freeModule = objectTypes[typeof module] && module && module.exports == freeExports && module; + + /** Detect free variable `global`, from Node.js or Browserified code, and use it as `window` */ + var freeGlobal = objectTypes[typeof global] && global; + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + window = freeGlobal; + } + + /*--------------------------------------------------------------------------*/ + + /** + * A basic implementation of `_.indexOf` without support for binary searches + * or `fromIndex` constraints. + * + * @private + * @param {Array} array The array to search. + * @param {Mixed} value The value to search for. + * @param {Number} [fromIndex=0] The index to search from. + * @returns {Number} Returns the index of the matched value or `-1`. + */ + function basicIndexOf(array, value, fromIndex) { + var index = (fromIndex || 0) - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * An implementation of `_.contains` for cache objects that mimics the return + * signature of `_.indexOf` by returning `0` if the value is found, else `-1`. + * + * @private + * @param {Object} cache The cache object to inspect. + * @param {Mixed} value The value to search for. + * @returns {Number} Returns `0` if `value` is found, else `-1`. + */ + function cacheIndexOf(cache, value) { + var type = typeof value; + cache = cache.cache; + + if (type == 'boolean' || value == null) { + return cache[value]; + } + if (type != 'number' && type != 'string') { + type = 'object'; + } + var key = type == 'number' ? value : keyPrefix + value; + cache = cache[type] || (cache[type] = {}); + + return type == 'object' + ? (cache[key] && basicIndexOf(cache[key], value) > -1 ? 0 : -1) + : (cache[key] ? 0 : -1); + } + + /** + * Adds a given `value` to the corresponding cache object. + * + * @private + * @param {Mixed} value The value to add to the cache. + */ + function cachePush(value) { + var cache = this.cache, + type = typeof value; + + if (type == 'boolean' || value == null) { + cache[value] = true; + } else { + if (type != 'number' && type != 'string') { + type = 'object'; + } + var key = type == 'number' ? value : keyPrefix + value, + typeCache = cache[type] || (cache[type] = {}); + + if (type == 'object') { + if ((typeCache[key] || (typeCache[key] = [])).push(value) == this.array.length) { + cache[type] = false; + } + } else { + typeCache[key] = true; + } + } + } + + /** + * Used by `_.max` and `_.min` as the default `callback` when a given + * `collection` is a string value. + * + * @private + * @param {String} value The character to inspect. + * @returns {Number} Returns the code unit of given character. + */ + function charAtCallback(value) { + return value.charCodeAt(0); + } + + /** + * Used by `sortBy` to compare transformed `collection` values, stable sorting + * them in ascending order. + * + * @private + * @param {Object} a The object to compare to `b`. + * @param {Object} b The object to compare to `a`. + * @returns {Number} Returns the sort order indicator of `1` or `-1`. + */ + function compareAscending(a, b) { + var ai = a.index, + bi = b.index; + + a = a.criteria; + b = b.criteria; + + // ensure a stable sort in V8 and other engines + // http://code.google.com/p/v8/issues/detail?id=90 + if (a !== b) { + if (a > b || typeof a == 'undefined') { + return 1; + } + if (a < b || typeof b == 'undefined') { + return -1; + } + } + return ai < bi ? -1 : 1; + } + + /** + * Creates a cache object to optimize linear searches of large arrays. + * + * @private + * @param {Array} [array=[]] The array to search. + * @returns {Null|Object} Returns the cache object or `null` if caching should not be used. + */ + function createCache(array) { + var index = -1, + length = array.length; + + var cache = getObject(); + cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false; + + var result = getObject(); + result.array = array; + result.cache = cache; + result.push = cachePush; + + while (++index < length) { + result.push(array[index]); + } + return cache.object === false + ? (releaseObject(result), null) + : result; + } + + /** + * Used by `template` to escape characters for inclusion in compiled + * string literals. + * + * @private + * @param {String} match The matched character to escape. + * @returns {String} Returns the escaped character. + */ + function escapeStringChar(match) { + return '\\' + stringEscapes[match]; + } + + /** + * Gets an array from the array pool or creates a new one if the pool is empty. + * + * @private + * @returns {Array} The array from the pool. + */ + function getArray() { + return arrayPool.pop() || []; + } + + /** + * Gets an object from the object pool or creates a new one if the pool is empty. + * + * @private + * @returns {Object} The object from the pool. + */ + function getObject() { + return objectPool.pop() || { + 'args': '', + 'array': null, + 'bottom': '', + 'cache': null, + 'criteria': null, + 'false': false, + 'firstArg': '', + 'index': 0, + 'init': '', + 'leading': false, + 'loop': '', + 'maxWait': 0, + 'null': false, + 'number': null, + 'object': null, + 'push': null, + 'shadowedProps': null, + 'string': null, + 'support': null, + 'top': '', + 'trailing': false, + 'true': false, + 'undefined': false, + 'useHas': false, + 'useKeys': false, + 'value': null + }; + } + + /** + * Checks if `value` is a DOM node in IE < 9. + * + * @private + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is a DOM node, else `false`. + */ + function isNode(value) { + // IE < 9 presents DOM nodes as `Object` objects except they have `toString` + // methods that are `typeof` "string" and still can coerce nodes to strings + return typeof value.toString != 'function' && typeof (value + '') == 'string'; + } + + /** + * A no-operation function. + * + * @private + */ + function noop() { + // no operation performed + } + + /** + * Releases the given `array` back to the array pool. + * + * @private + * @param {Array} [array] The array to release. + */ + function releaseArray(array) { + array.length = 0; + if (arrayPool.length < maxPoolSize) { + arrayPool.push(array); + } + } + + /** + * Releases the given `object` back to the object pool. + * + * @private + * @param {Object} [object] The object to release. + */ + function releaseObject(object) { + var cache = object.cache; + if (cache) { + releaseObject(cache); + } + object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null; + if (objectPool.length < maxPoolSize) { + objectPool.push(object); + } + } + + /** + * Slices the `collection` from the `start` index up to, but not including, + * the `end` index. + * + * Note: This function is used, instead of `Array#slice`, to support node lists + * in IE < 9 and to ensure dense arrays are returned. + * + * @private + * @param {Array|Object|String} collection The collection to slice. + * @param {Number} start The start index. + * @param {Number} end The end index. + * @returns {Array} Returns the new array. + */ + function slice(array, start, end) { + start || (start = 0); + if (typeof end == 'undefined') { + end = array ? array.length : 0; + } + var index = -1, + length = end - start || 0, + result = Array(length < 0 ? 0 : length); + + while (++index < length) { + result[index] = array[start + index]; + } + return result; + } + /*--------------------------------------------------------------------------*/ /** @@ -157,6 +455,7 @@ var Array = context.Array, Boolean = context.Boolean, Date = context.Date, + Error = context.Error, Function = context.Function, Math = context.Math, Number = context.Number, @@ -165,16 +464,25 @@ String = context.String, TypeError = context.TypeError; - /** Used for `Array` and `Object` method references */ - var arrayRef = Array(), - objectRef = Object(); + /** + * Used for `Array` method references. + * + * Normally `Array.prototype` would suffice, however, using an array literal + * avoids issues in Narwhal. + */ + var arrayRef = []; + + /** Used for native method references */ + var errorProto = Error.prototype, + objectProto = Object.prototype, + stringProto = String.prototype; /** Used to restore the original `_` reference in `noConflict` */ var oldDash = context._; /** Used to detect if a method is native */ var reNative = RegExp('^' + - String(objectRef.valueOf) + String(objectProto.valueOf) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/valueOf|for [^\]]+/g, '.+?') + '$' ); @@ -184,15 +492,18 @@ clearTimeout = context.clearTimeout, concat = arrayRef.concat, floor = Math.floor, + fnToString = Function.prototype.toString, getPrototypeOf = reNative.test(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, - hasOwnProperty = objectRef.hasOwnProperty, + hasOwnProperty = objectProto.hasOwnProperty, push = arrayRef.push, + propertyIsEnumerable = objectProto.propertyIsEnumerable, setImmediate = context.setImmediate, setTimeout = context.setTimeout, - toString = objectRef.toString; + toString = objectProto.toString; /* Native method shortcuts for methods with the same name as other `lodash` methods */ var nativeBind = reNative.test(nativeBind = toString.bind) && nativeBind, + nativeCreate = reNative.test(nativeCreate = Object.create) && nativeCreate, nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray, nativeIsFinite = context.isFinite, nativeIsNaN = context.isNaN, @@ -212,11 +523,31 @@ ctorByClass[arrayClass] = Array; ctorByClass[boolClass] = Boolean; ctorByClass[dateClass] = Date; + ctorByClass[funcClass] = Function; ctorByClass[objectClass] = Object; ctorByClass[numberClass] = Number; ctorByClass[regexpClass] = RegExp; ctorByClass[stringClass] = String; + /** Used to avoid iterating non-enumerable properties in IE < 9 */ + var nonEnumProps = {}; + nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; + nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; + nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; + nonEnumProps[objectClass] = { 'constructor': true }; + + (function() { + var length = shadowedProps.length; + while (length--) { + var prop = shadowedProps[length]; + for (var className in nonEnumProps) { + if (hasOwnProperty.call(nonEnumProps, className) && !hasOwnProperty.call(nonEnumProps[className], prop)) { + nonEnumProps[className][prop] = false; + } + } + } + }()); + /*--------------------------------------------------------------------------*/ /** @@ -238,8 +569,8 @@ * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `push`, `range`, * `reject`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, `sortBy`, `splice`, - * `tap`, `throttle`, `times`, `toArray`, `union`, `uniq`, `unshift`, `unzip`, - * `values`, `where`, `without`, `wrap`, and `zip` + * `tap`, `throttle`, `times`, `toArray`, `transform`, `union`, `uniq`, `unshift`, + * `unzip`, `values`, `where`, `without`, `wrap`, and `zip` * * The non-chainable wrapper functions are: * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `has`, @@ -255,6 +586,7 @@ * * @name _ * @constructor + * @alias chain * @category Chaining * @param {Mixed} value The value to wrap in a `lodash` instance. * @returns {Object} Returns a `lodash` instance. @@ -286,6 +618,19 @@ : new lodashWrapper(value); } + /** + * A fast path for creating `lodash` wrapper objects. + * + * @private + * @param {Mixed} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns a `lodash` instance. + */ + function lodashWrapper(value) { + this.__wrapped__ = value; + } + // ensure `new lodashWrapper` is an instance of `lodash` + lodashWrapper.prototype = lodash.prototype; + /** * An object used to flag environments features. * @@ -320,6 +665,15 @@ */ support.argsClass = isArguments(arguments); + /** + * Detect if `name` or `message` properties of `Error.prototype` are + * enumerable by default. (IE < 9, Safari < 5.1) + * + * @memberOf _.support + * @type Boolean + */ + support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); + /** * Detect if `prototype` properties are enumerable by default. * @@ -331,7 +685,7 @@ * @memberOf _.support * @type Boolean */ - support.enumPrototypes = ctor.propertyIsEnumerable('prototype'); + support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); /** * Detect if `Function#bind` exists and is inferred to be fast (all but V8). @@ -487,12 +841,12 @@ // exit early if the first argument is falsey 'if (!iterable) return result;\n' + // add code before the iteration branches - '<%= top %>;\n' + + '<%= top %>;' + // array-like iteration: - '<% if (arrays) { %>' + + '<% if (array) { %>\n' + 'var length = iterable.length; index = -1;\n' + - 'if (<%= arrays %>) {' + + 'if (<%= array %>) {' + // add support for accessing string characters by index if needed ' <% if (support.unindexedChars) { %>\n' + @@ -503,19 +857,19 @@ // iterate over the array-like value ' while (++index < length) {\n' + - ' <%= loop %>\n' + + ' <%= loop %>;\n' + ' }\n' + '}\n' + 'else {' + // object iteration: // add support for iterating over `arguments` objects if needed - ' <% } else if (support.nonEnumArgs) { %>\n' + + ' <% } else if (support.nonEnumArgs) { %>\n' + ' var length = iterable.length; index = -1;\n' + ' if (length && isArguments(iterable)) {\n' + ' while (++index < length) {\n' + " index += '';\n" + - ' <%= loop %>\n' + + ' <%= loop %>;\n' + ' }\n' + ' } else {' + ' <% } %>' + @@ -525,29 +879,37 @@ " var skipProto = typeof iterable == 'function';\n" + ' <% } %>' + - // iterate own properties using `Object.keys` if it's fast + // avoid iterating over `Error.prototype` properties in older IE and Safari + ' <% if (support.enumErrorProps) { %>\n' + + ' var skipErrorProps = iterable === errorProto || iterable instanceof Error;\n' + + ' <% } %>' + + + // define conditions used in the loop + ' <%' + + ' var conditions = [];' + + ' if (support.enumPrototypes) { conditions.push(\'!(skipProto && index == "prototype")\'); }' + + ' if (support.enumErrorProps) { conditions.push(\'!(skipErrorProps && (index == "message" || index == "name"))\'); }' + + ' %>' + + + // iterate own properties using `Object.keys` ' <% if (useHas && useKeys) { %>\n' + ' var ownIndex = -1,\n' + - ' ownProps = objectTypes[typeof iterable] ? keys(iterable) : [],\n' + - ' length = ownProps.length;\n\n' + + ' ownProps = objectTypes[typeof iterable] && keys(iterable),\n' + + ' length = ownProps ? ownProps.length : 0;\n\n' + ' while (++ownIndex < length) {\n' + - ' index = ownProps[ownIndex];\n' + - " <% if (support.enumPrototypes) { %>if (!(skipProto && index == 'prototype')) {\n <% } %>" + - ' <%= loop %>\n' + - ' <% if (support.enumPrototypes) { %>}\n<% } %>' + + ' index = ownProps[ownIndex];\n<%' + + " if (conditions.length) { %> if (<%= conditions.join(' && ') %>) {\n <% } %>" + + ' <%= loop %>;' + + ' <% if (conditions.length) { %>\n }<% } %>\n' + ' }' + // else using a for-in loop ' <% } else { %>\n' + - ' for (index in iterable) {<%' + - ' if (support.enumPrototypes || useHas) { %>\n if (<%' + - " if (support.enumPrototypes) { %>!(skipProto && index == 'prototype')<% }" + - ' if (support.enumPrototypes && useHas) { %> && <% }' + - ' if (useHas) { %>hasOwnProperty.call(iterable, index)<% }' + - ' %>) {' + - ' <% } %>\n' + + ' for (index in iterable) {\n<%' + + ' if (useHas) { conditions.push("hasOwnProperty.call(iterable, index)"); }' + + " if (conditions.length) { %> if (<%= conditions.join(' && ') %>) {\n <% } %>" + ' <%= loop %>;' + - ' <% if (support.enumPrototypes || useHas) { %>\n }<% } %>\n' + + ' <% if (conditions.length) { %>\n }<% } %>\n' + ' }' + // Because IE < 9 can't set the `[[Enumerable]]` attribute of an @@ -555,19 +917,23 @@ // defaults to non-enumerable, Lo-Dash skips the `constructor` // property when it infers it's iterating over a `prototype` object. ' <% if (support.nonEnumShadows) { %>\n\n' + - ' var ctor = iterable.constructor;\n' + - ' <% for (var k = 0; k < 7; k++) { %>\n' + - " index = '<%= shadowedProps[k] %>';\n" + - ' if (<%' + - " if (shadowedProps[k] == 'constructor') {" + - ' %>!(ctor && ctor.prototype === iterable) && <%' + - ' } %>hasOwnProperty.call(iterable, index)) {\n' + - ' <%= loop %>\n' + + ' if (iterable !== objectProto) {\n' + + " var ctor = iterable.constructor,\n" + + ' isProto = iterable === (ctor && ctor.prototype),\n' + + ' className = iterable === stringProto ? stringClass : iterable === errorProto ? errorClass : toString.call(iterable),\n' + + ' nonEnum = nonEnumProps[className];\n' + + ' <% for (k = 0; k < 7; k++) { %>\n' + + " index = '<%= shadowedProps[k] %>';\n" + + ' if ((!(isProto && nonEnum[index]) && hasOwnProperty.call(iterable, index))<%' + + ' if (!useHas) { %> || (!nonEnum[index] && iterable[index] !== objectProto[index])<% }' + + ' %>) {\n' + + ' <%= loop %>;\n' + + ' }' + + ' <% } %>\n' + ' }' + - ' <% } %>' + ' <% } %>' + ' <% } %>' + - ' <% if (arrays || support.nonEnumArgs) { %>\n}<% } %>\n' + + ' <% if (array || support.nonEnumArgs) { %>\n}<% } %>\n' + // add code to the bottom of the iteration function '<%= bottom %>;\n' + @@ -593,90 +959,18 @@ var eachIteratorOptions = { 'args': 'collection, callback, thisArg', 'top': "callback = callback && typeof thisArg == 'undefined' ? callback : lodash.createCallback(callback, thisArg)", - 'arrays': "typeof length == 'number'", + 'array': "typeof length == 'number'", 'loop': 'if (callback(iterable[index], index, collection) === false) return result' }; /** Reusable iterator options for `forIn` and `forOwn` */ var forOwnIteratorOptions = { 'top': 'if (!objectTypes[typeof iterable]) return result;\n' + eachIteratorOptions.top, - 'arrays': false + 'array': false }; /*--------------------------------------------------------------------------*/ - /** - * Creates a function optimized to search large arrays for a given `value`, - * starting at `fromIndex`, using strict equality for comparisons, i.e. `===`. - * - * @private - * @param {Array} array The array to search. - * @param {Mixed} value The value to search for. - * @returns {Boolean} Returns `true`, if `value` is found, else `false`. - */ - function cachedContains(array) { - var length = array.length, - isLarge = length >= largeArraySize; - - if (isLarge) { - var cache = {}, - index = -1; - - while (++index < length) { - var key = keyPrefix + array[index]; - (cache[key] || (cache[key] = [])).push(array[index]); - } - } - return function(value) { - if (isLarge) { - var key = keyPrefix + value; - return cache[key] && indexOf(cache[key], value) > -1; - } - return indexOf(array, value) > -1; - } - } - - /** - * Used by `_.max` and `_.min` as the default `callback` when a given - * `collection` is a string value. - * - * @private - * @param {String} value The character to inspect. - * @returns {Number} Returns the code unit of given character. - */ - function charAtCallback(value) { - return value.charCodeAt(0); - } - - /** - * Used by `sortBy` to compare transformed `collection` values, stable sorting - * them in ascending order. - * - * @private - * @param {Object} a The object to compare to `b`. - * @param {Object} b The object to compare to `a`. - * @returns {Number} Returns the sort order indicator of `1` or `-1`. - */ - function compareAscending(a, b) { - var ai = a.index, - bi = b.index; - - a = a.criteria; - b = b.criteria; - - // ensure a stable sort in V8 and other engines - // http://code.google.com/p/v8/issues/detail?id=90 - if (a !== b) { - if (a > b || typeof a == 'undefined') { - return 1; - } - if (a < b || typeof b == 'undefined') { - return -1; - } - } - return ai < bi ? -1 : 1; - } - /** * Creates a function that, when called, invokes `func` with the `this` binding * of `thisArg` and prepends any `partialArgs` to the arguments passed to the @@ -723,9 +1017,7 @@ } if (this instanceof bound) { // ensure `new bound` is an instance of `func` - noop.prototype = func.prototype; - thisBinding = new noop; - noop.prototype = null; + thisBinding = createObject(func.prototype); // mimic the constructor's `return` behavior // http://es5.github.com/#x13.2.2 @@ -742,7 +1034,7 @@ * * @private * @param {Object} [options1, options2, ...] The compile options object(s). - * arrays - A string of code to determine if the iterable is an array or array-like. + * array - A string of code to determine if the iterable is an array or array-like. * useHas - A boolean to specify using `hasOwnProperty` checks in the object loop. * useKeys - A boolean to specify using `_.keys` for own property iteration. * args - A string of comma separated arguments the iteration function will accept. @@ -752,20 +1044,17 @@ * @returns {Function} Returns the compiled function. */ function createIterator() { - var data = { - // data properties - 'shadowedProps': shadowedProps, - 'support': support, - - // iterator options - 'arrays': 'isArray(iterable)', - 'bottom': '', - 'init': 'iterable', - 'loop': '', - 'top': '', - 'useHas': true, - 'useKeys': !!keys - }; + var data = getObject(); + + // data properties + data.shadowedProps = shadowedProps; + data.support = support; + + // iterator options + data.array = data.bottom = data.loop = data.top = ''; + data.init = 'iterable'; + data.useHas = true; + data.useKeys = !!keys; // merge options into a template data object for (var object, index = 0; object = arguments[index]; index++) { @@ -778,27 +1067,42 @@ // create the function factory var factory = Function( - 'hasOwnProperty, isArguments, isArray, isString, keys, ' + - 'lodash, objectTypes', + 'errorClass, errorProto, hasOwnProperty, isArguments, isArray, ' + + 'isString, keys, lodash, objectProto, objectTypes, nonEnumProps, ' + + 'stringClass, stringProto, toString', 'return function(' + args + ') {\n' + iteratorTemplate(data) + '\n}' ); + + releaseObject(data); + // return the compiled function return factory( - hasOwnProperty, isArguments, isArray, isString, keys, - lodash, objectTypes + errorClass, errorProto, hasOwnProperty, isArguments, isArray, + isString, keys, lodash, objectProto, objectTypes, nonEnumProps, + stringClass, stringProto, toString ); } /** - * Used by `template` to escape characters for inclusion in compiled - * string literals. + * Creates a new object with the specified `prototype`. * * @private - * @param {String} match The matched character to escape. - * @returns {String} Returns the escaped character. + * @param {Object} prototype The prototype object. + * @returns {Object} Returns the new object. */ - function escapeStringChar(match) { - return '\\' + stringEscapes[match]; + function createObject(prototype) { + return isObject(prototype) ? nativeCreate(prototype) : {}; + } + // fallback for browsers without `Object.create` + if (!nativeCreate) { + var createObject = function(prototype) { + if (isObject(prototype)) { + noop.prototype = prototype; + var result = new noop; + noop.prototype = null; + } + return result || {}; + }; } /** @@ -813,38 +1117,39 @@ } /** - * Checks if `value` is a DOM node in IE < 9. - * - * @private - * @param {Mixed} value The value to check. - * @returns {Boolean} Returns `true` if the `value` is a DOM node, else `false`. - */ - function isNode(value) { - // IE < 9 presents DOM nodes as `Object` objects except they have `toString` - // methods that are `typeof` "string" and still can coerce nodes to strings - return typeof value.toString != 'function' && typeof (value + '') == 'string'; - } - - /** - * A fast path for creating `lodash` wrapper objects. + * Gets the appropriate "indexOf" function. If the `_.indexOf` method is + * customized, this method returns the custom method, otherwise it returns + * the `basicIndexOf` function. * * @private - * @param {Mixed} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns a `lodash` instance. + * @returns {Function} Returns the "indexOf" function. */ - function lodashWrapper(value) { - this.__wrapped__ = value; + function getIndexOf(array, value, fromIndex) { + var result = (result = lodash.indexOf) === indexOf ? basicIndexOf : result; + return result; } - // ensure `new lodashWrapper` is an instance of `lodash` - lodashWrapper.prototype = lodash.prototype; /** - * A no-operation function. + * Creates a function that juggles arguments, allowing argument overloading + * for `_.flatten` and `_.uniq`, before passing them to the given `func`. * * @private + * @param {Function} func The function to wrap. + * @returns {Function} Returns the new function. */ - function noop() { - // no operation performed + function overloadWrapper(func) { + return function(array, flag, callback, thisArg) { + // juggle arguments + if (typeof flag != 'boolean' && flag != null) { + thisArg = callback; + callback = !(thisArg && thisArg[flag] === array) ? flag : undefined; + flag = false; + } + if (callback != null) { + callback = lodash.createCallback(callback, thisArg); + } + return func(array, flag, callback, thisArg); + }; } /** @@ -858,62 +1163,33 @@ * @returns {Boolean} Returns `true`, if `value` is a plain object, else `false`. */ function shimIsPlainObject(value) { - // avoid non-objects and false positives for `arguments` objects - var result = false; - if (!(value && toString.call(value) == objectClass) || (!support.argsClass && isArguments(value))) { - return result; - } - // check that the constructor is `Object` (i.e. `Object instanceof Object`) - var ctor = value.constructor; - - if (isFunction(ctor) ? ctor instanceof ctor : (support.nodeClass || !isNode(value))) { - // IE < 9 iterates inherited properties before own properties. If the first - // iterated property is an object's own property then there are no inherited - // enumerable properties. - if (support.ownLast) { - forIn(value, function(value, key, object) { - result = hasOwnProperty.call(object, key); - return false; - }); - return result === true; - } - // In most environments an object's own properties are iterated before - // its inherited properties. If the last iterated property is an object's - // own property then there are no inherited enumerable properties. - forIn(value, function(value, key) { - result = key; - }); - return result === false || hasOwnProperty.call(value, result); - } - return result; - } + var ctor, + result; - /** - * Slices the `collection` from the `start` index up to, but not including, - * the `end` index. - * - * Note: This function is used, instead of `Array#slice`, to support node lists - * in IE < 9 and to ensure dense arrays are returned. - * - * @private - * @param {Array|Object|String} collection The collection to slice. - * @param {Number} start The start index. - * @param {Number} end The end index. - * @returns {Array} Returns the new array. - */ - function slice(array, start, end) { - start || (start = 0); - if (typeof end == 'undefined') { - end = array ? array.length : 0; + // avoid non Object objects, `arguments` objects, and DOM elements + if (!(value && toString.call(value) == objectClass) || + (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor)) || + (!support.argsClass && isArguments(value)) || + (!support.nodeClass && isNode(value))) { + return false; } - var index = -1, - length = end - start || 0, - result = Array(length < 0 ? 0 : length); - - while (++index < length) { - result[index] = array[start + index]; + // IE < 9 iterates inherited properties before own properties. If the first + // iterated property is an object's own property then there are no inherited + // enumerable properties. + if (support.ownLast) { + forIn(value, function(value, key, object) { + result = hasOwnProperty.call(object, key); + return false; + }); + return result !== false; } - return result; + // In most environments an object's own properties are iterated before + // its inherited properties. If the last iterated property is an object's + // own property then there are no inherited enumerable properties. + forIn(value, function(value, key) { + result = key; + }); + return result === undefined || hasOwnProperty.call(value, result); } /** @@ -988,8 +1264,7 @@ 'args': 'object', 'init': '[]', 'top': 'if (!(objectTypes[typeof object])) return result', - 'loop': 'result.push(index)', - 'arrays': false + 'loop': 'result.push(index)' }); /** @@ -1030,7 +1305,7 @@ * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|String} Returns `collection`. */ - var each = createIterator(eachIteratorOptions); + var basicEach = createIterator(eachIteratorOptions); /** * Used to convert characters to HTML entities: @@ -1143,7 +1418,7 @@ // allows working with "Collections" methods without using their `callback` // argument, `index|key`, for this method's `callback` - if (typeof deep == 'function') { + if (typeof deep != 'boolean' && deep != null) { thisArg = callback; callback = deep; deep = false; @@ -1188,8 +1463,9 @@ return ctor(result.source, reFlags.exec(result)); } // check for circular references and return corresponding clone - stackA || (stackA = []); - stackB || (stackB = []); + var initedStack = !stackA; + stackA || (stackA = getArray()); + stackB || (stackB = getArray()); var length = stackA.length; while (length--) { @@ -1215,10 +1491,14 @@ stackB.push(result); // recursively populate clone (susceptible to call stack limits) - (isArr ? forEach : forOwn)(value, function(objValue, key) { + (isArr ? basicEach : forOwn)(value, function(objValue, key) { result[key] = clone(objValue, deep, callback, undefined, stackA, stackB); }); + if (initedStack) { + releaseArray(stackA); + releaseArray(stackB); + } return result; } @@ -1228,7 +1508,7 @@ * `undefined`, cloning will be handled by the method instead. The `callback` * is bound to `thisArg` and invoked with one argument; (value). * - * Note: This function is loosely based on the structured clone algorithm. Functions + * Note: This method is loosely based on the structured clone algorithm. Functions * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and * objects created by constructors other than `Object` are cloned to plain `Object` objects. * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm. @@ -1665,8 +1945,9 @@ // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.com/#x15.12.3) - stackA || (stackA = []); - stackB || (stackB = []); + var initedStack = !stackA; + stackA || (stackA = getArray()); + stackB || (stackB = getArray()); var length = stackA.length; while (length--) { @@ -1728,6 +2009,10 @@ } }); } + if (initedStack) { + releaseArray(stackA); + releaseArray(stackB); + } return result; } @@ -1811,7 +2096,7 @@ // http://es5.github.com/#x8 // and avoid a V8 bug // http://code.google.com/p/v8/issues/detail?id=2291 - return value ? objectTypes[typeof value] : false; + return !!(value && objectTypes[typeof value]); } /** @@ -1932,7 +2217,7 @@ * // => true */ function isRegExp(value) { - return value ? (objectTypes[typeof value] && toString.call(value) == regexpClass) : false; + return !!(value && objectTypes[typeof value]) && toString.call(value) == regexpClass; } /** @@ -2037,8 +2322,9 @@ stackA = args[4], stackB = args[5]; } else { - stackA = []; - stackB = []; + var initedStack = true; + stackA = getArray(); + stackB = getArray(); // allows working with `_.reduce` and `_.reduceRight` without // using their `callback` arguments, `index|key` and `collection` @@ -2104,6 +2390,11 @@ object[key] = value; }); } + + if (initedStack) { + releaseArray(stackA); + releaseArray(stackB); + } return object; } @@ -2134,7 +2425,8 @@ * // => { 'name': 'moe' } */ function omit(object, callback, thisArg) { - var isFunc = typeof callback == 'function', + var indexOf = getIndexOf(), + isFunc = typeof callback == 'function', result = {}; if (isFunc) { @@ -2229,6 +2521,57 @@ return result; } + /** + * An alternative to `_.reduce`, this method transforms an `object` to a new + * `accumulator` object which is the result of running each of its elements + * through the `callback`, with each `callback` execution potentially mutating + * the `accumulator` object. The `callback` is bound to `thisArg` and invoked + * with four arguments; (accumulator, value, key, object). Callbacks may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [accumulator] The custom accumulator value. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Mixed} Returns the accumulated value. + * @example + * + * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) { + * num *= num; + * if (num % 2) { + * return result.push(num) < 3; + * } + * }); + * // => [1, 9, 25] + * + * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { + * result[key] = num * 3; + * }); + * // => { 'a': 3, 'b': 6, 'c': 9 } + */ + function transform(object, callback, accumulator, thisArg) { + var isArr = isArray(object); + callback = lodash.createCallback(callback, thisArg, 4); + + if (accumulator == null) { + if (isArr) { + accumulator = []; + } else { + var ctor = object && object.constructor, + proto = ctor && ctor.prototype; + + accumulator = createObject(proto); + } + } + (isArr ? basicEach : forOwn)(object, function(value, index, object) { + return callback(accumulator, value, index, object); + }); + return accumulator; + } + /** * Creates an array composed of the own enumerable property values of `object`. * @@ -2321,17 +2664,18 @@ */ function contains(collection, target, fromIndex) { var index = -1, + indexOf = getIndexOf(), length = collection ? collection.length : 0, result = false; fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0; - if (typeof length == 'number') { + if (length && typeof length == 'number') { result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex) ) > -1; } else { - each(collection, function(value) { + basicEach(collection, function(value) { if (++index >= fromIndex) { return !(result = value === target); } @@ -2439,7 +2783,7 @@ } } } else { - each(collection, function(value, index, collection) { + basicEach(collection, function(value, index, collection) { return (result = !!callback(value, index, collection)); }); } @@ -2501,7 +2845,7 @@ } } } else { - each(collection, function(value, index, collection) { + basicEach(collection, function(value, index, collection) { if (callback(value, index, collection)) { result.push(value); } @@ -2524,7 +2868,7 @@ * * @static * @memberOf _ - * @alias detect + * @alias detect, findWhere * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per @@ -2568,7 +2912,7 @@ } } else { var result; - each(collection, function(value, index, collection) { + basicEach(collection, function(value, index, collection) { if (callback(value, index, collection)) { result = value; return false; @@ -2611,7 +2955,7 @@ } } } else { - each(collection, callback, thisArg); + basicEach(collection, callback, thisArg); } return collection; } @@ -2746,7 +3090,7 @@ result[index] = callback(collection[index], index, collection); } } else { - each(collection, function(value, key, collection) { + basicEach(collection, function(value, key, collection) { result[++index] = callback(value, key, collection); }); } @@ -2811,7 +3155,7 @@ ? charAtCallback : lodash.createCallback(callback, thisArg); - each(collection, function(value, index, collection) { + basicEach(collection, function(value, index, collection) { var current = callback(value, index, collection); if (current > computed) { computed = current; @@ -2880,7 +3224,7 @@ ? charAtCallback : lodash.createCallback(callback, thisArg); - each(collection, function(value, index, collection) { + basicEach(collection, function(value, index, collection) { var current = callback(value, index, collection); if (current < computed) { computed = current; @@ -2958,7 +3302,7 @@ accumulator = callback(accumulator, collection[index], index, collection); } } else { - each(collection, function(value, index, collection) { + basicEach(collection, function(value, index, collection) { accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, collection) @@ -3161,7 +3505,7 @@ } } } else { - each(collection, function(value, index, collection) { + basicEach(collection, function(value, index, collection) { return !(result = callback(value, index, collection)); }); } @@ -3210,17 +3554,18 @@ callback = lodash.createCallback(callback, thisArg); forEach(collection, function(value, key, collection) { - result[++index] = { - 'criteria': callback(value, key, collection), - 'index': index, - 'value': value - }; + var object = result[++index] = getObject(); + object.criteria = callback(value, key, collection); + object.index = index; + object.value = value; }); length = result.length; result.sort(compareAscending); while (length--) { - result[length] = result[length].value; + var object = result[length]; + result[length] = object.value; + releaseObject(object); } return result; } @@ -3320,17 +3665,31 @@ */ function difference(array) { var index = -1, + indexOf = getIndexOf(), length = array ? array.length : 0, - flattened = concat.apply(arrayRef, nativeSlice.call(arguments, 1)), - contains = cachedContains(flattened), + seen = concat.apply(arrayRef, nativeSlice.call(arguments, 1)), result = []; + var isLarge = length >= largeArraySize && indexOf === basicIndexOf; + + if (isLarge) { + var cache = createCache(seen); + if (cache) { + indexOf = cacheIndexOf; + seen = cache; + } else { + isLarge = false; + } + } while (++index < length) { var value = array[index]; - if (!contains(value)) { + if (indexOf(seen, value) < 0) { result.push(value); } } + if (isLarge) { + releaseObject(seen); + } return result; } @@ -3486,20 +3845,11 @@ * _.flatten(stooges, 'quotes'); * // => ['Oh, a wise guy, eh?', 'Poifect!', 'Spread out!', 'You knucklehead!'] */ - function flatten(array, isShallow, callback, thisArg) { + var flatten = overloadWrapper(function flatten(array, isShallow, callback) { var index = -1, length = array ? array.length : 0, result = []; - // juggle arguments - if (typeof isShallow != 'boolean' && isShallow != null) { - thisArg = callback; - callback = isShallow; - isShallow = false; - } - if (callback != null) { - callback = lodash.createCallback(callback, thisArg); - } while (++index < length) { var value = array[index]; if (callback) { @@ -3513,7 +3863,7 @@ } } return result; - } + }); /** * Gets the index at which the first occurrence of `value` is found using @@ -3540,21 +3890,14 @@ * // => 2 */ function indexOf(array, value, fromIndex) { - var index = -1, - length = array ? array.length : 0; - if (typeof fromIndex == 'number') { - index = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0) - 1; + var length = array ? array.length : 0; + fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0); } else if (fromIndex) { - index = sortedIndex(array, value); + var index = sortedIndex(array, value); return array[index] === value ? index : -1; } - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; + return array ? basicIndexOf(array, value, fromIndex) : -1; } /** @@ -3650,35 +3993,45 @@ function intersection(array) { var args = arguments, argsLength = args.length, - cache = { '0': {} }, + argsIndex = -1, + caches = getArray(), index = -1, + indexOf = getIndexOf(), length = array ? array.length : 0, - isLarge = length >= largeArraySize, result = [], - seen = result; + seen = getArray(); + while (++argsIndex < argsLength) { + var value = args[argsIndex]; + caches[argsIndex] = indexOf === basicIndexOf && + (value ? value.length : 0) >= largeArraySize && + createCache(argsIndex ? args[argsIndex] : seen); + } outer: while (++index < length) { - var value = array[index]; - if (isLarge) { - var key = keyPrefix + value; - var inited = cache[0][key] - ? !(seen = cache[0][key]) - : (seen = cache[0][key] = []); - } - if (inited || indexOf(seen, value) < 0) { - if (isLarge) { - seen.push(value); - } - var argsIndex = argsLength; + var cache = caches[0]; + value = array[index]; + + if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) { + argsIndex = argsLength; + (cache || seen).push(value); while (--argsIndex) { - if (!(cache[argsIndex] || (cache[argsIndex] = cachedContains(args[argsIndex])))(value)) { + cache = caches[argsIndex]; + if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) { continue outer; } } result.push(value); } } + while (argsLength--) { + cache = caches[argsLength]; + if (cache) { + releaseObject(cache); + } + } + releaseArray(caches); + releaseArray(seen); return result; } @@ -4007,7 +4360,7 @@ * Creates a duplicate-value-free version of the `array` using strict equality * for comparisons, i.e. `===`. If the `array` is already sorted, passing `true` * for `isSorted` will run a faster algorithm. If `callback` is passed, each - * element of `array` is passed through a `callback` before uniqueness is computed. + * element of `array` is passed through the `callback` before uniqueness is computed. * The `callback` is bound to `thisArg` and invoked with three arguments; (value, index, array). * * If a property name is passed for `callback`, the created "_.pluck" style @@ -4036,50 +4389,42 @@ * _.uniq([1, 1, 2, 2, 3], true); * // => [1, 2, 3] * - * _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return Math.floor(num); }); - * // => [1, 2, 3] + * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); }); + * // => ['A', 'b', 'C'] * - * _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math); - * // => [1, 2, 3] + * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math); + * // => [1, 2.5, 3] * * // using "_.pluck" callback shorthand * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ - function uniq(array, isSorted, callback, thisArg) { + var uniq = overloadWrapper(function(array, isSorted, callback) { var index = -1, + indexOf = getIndexOf(), length = array ? array.length : 0, - result = [], - seen = result; + result = []; + + var isLarge = !isSorted && length >= largeArraySize && indexOf === basicIndexOf, + seen = (callback || isLarge) ? getArray() : result; - // juggle arguments - if (typeof isSorted != 'boolean' && isSorted != null) { - thisArg = callback; - callback = isSorted; - isSorted = false; - } - // init value cache for large arrays - var isLarge = !isSorted && length >= largeArraySize; if (isLarge) { - var cache = {}; - } - if (callback != null) { - seen = []; - callback = lodash.createCallback(callback, thisArg); + var cache = createCache(seen); + if (cache) { + indexOf = cacheIndexOf; + seen = cache; + } else { + isLarge = false; + seen = callback ? seen : (releaseArray(seen), result); + } } while (++index < length) { var value = array[index], computed = callback ? callback(value, index, array) : value; - if (isLarge) { - var key = keyPrefix + computed; - var inited = cache[key] - ? !(seen = cache[key]) - : (seen = cache[key] = []); - } if (isSorted ? !index || seen[seen.length - 1] !== computed - : inited || indexOf(seen, computed) < 0 + : indexOf(seen, computed) < 0 ) { if (callback || isLarge) { seen.push(computed); @@ -4087,8 +4432,14 @@ result.push(value); } } + if (isLarge) { + releaseArray(seen.array); + releaseObject(seen); + } else if (callback) { + releaseArray(seen); + } return result; - } + }); /** * The inverse of `_.zip`, this method splits groups of elements into arrays @@ -4106,17 +4457,11 @@ */ function unzip(array) { var index = -1, - length = array ? array.length : 0, - tupleLength = length ? max(pluck(array, 'length')) : 0, - result = Array(tupleLength); + length = array ? max(pluck(array, 'length')) : 0, + result = Array(length < 0 ? 0 : length); while (++index < length) { - var tupleIndex = -1, - tuple = array[index]; - - while (++tupleIndex < tupleLength) { - (result[tupleIndex] || (result[tupleIndex] = Array(length)))[index] = tuple[tupleIndex]; - } + result[index] = pluck(array, index); } return result; } @@ -4157,14 +4502,7 @@ * // => [['moe', 30, true], ['larry', 40, false]] */ function zip(array) { - var index = -1, - length = array ? max(pluck(arguments, 'length')) : 0, - result = Array(length); - - while (++index < length) { - result[index] = pluck(arguments, index); - } - return result; + return array ? unzip(arguments) : []; } /** @@ -4440,27 +4778,27 @@ return result; }; } - if (typeof thisArg != 'undefined') { - if (argCount === 1) { - return function(value) { - return func.call(thisArg, value); - }; - } - if (argCount === 2) { - return function(a, b) { - return func.call(thisArg, a, b); - }; - } - if (argCount === 4) { - return function(accumulator, value, index, collection) { - return func.call(thisArg, accumulator, value, index, collection); - }; - } - return function(value, index, collection) { - return func.call(thisArg, value, index, collection); + if (typeof thisArg == 'undefined' || (reThis && !reThis.test(fnToString.call(func)))) { + return func; + } + if (argCount === 1) { + return function(value) { + return func.call(thisArg, value); }; } - return func; + if (argCount === 2) { + return function(a, b) { + return func.call(thisArg, a, b); + }; + } + if (argCount === 4) { + return function(accumulator, value, index, collection) { + return func.call(thisArg, accumulator, value, index, collection); + }; + } + return function(value, index, collection) { + return func.call(thisArg, value, index, collection); + }; } /** @@ -4481,6 +4819,7 @@ * @param {Number} wait The number of milliseconds to delay. * @param {Object} options The options object. * [leading=false] A boolean to specify execution on the leading edge of the timeout. + * [maxWait] The maximum time `func` is allowed to be delayed before it's called. * [trailing=true] A boolean to specify execution on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example @@ -4495,34 +4834,80 @@ */ function debounce(func, wait, options) { var args, - inited, result, thisArg, - timeoutId, + callCount = 0, + lastCalled = 0, + maxWait = false, + maxTimeoutId = null, + timeoutId = null, trailing = true; + function clear() { + clearTimeout(maxTimeoutId); + clearTimeout(timeoutId); + callCount = 0; + maxTimeoutId = timeoutId = null; + } + function delayed() { - inited = timeoutId = null; - if (trailing) { + var isCalled = trailing && (!leading || callCount > 1); + clear(); + if (isCalled) { + if (maxWait !== false) { + lastCalled = new Date; + } + result = func.apply(thisArg, args); + } + } + + function maxDelayed() { + clear(); + if (trailing || (maxWait !== wait)) { + lastCalled = new Date; result = func.apply(thisArg, args); } } + + wait = nativeMax(0, wait || 0); if (options === true) { var leading = true; trailing = false; - } else if (options && objectTypes[typeof options]) { + } else if (isObject(options)) { leading = options.leading; + maxWait = 'maxWait' in options && nativeMax(wait, options.maxWait || 0); trailing = 'trailing' in options ? options.trailing : trailing; } return function() { args = arguments; thisArg = this; + callCount++; + + // avoid issues with Titanium and `undefined` timeout ids + // https://github.com/appcelerator/titanium_mobile/blob/3_1_0_GA/android/titanium/src/java/ti/modules/titanium/TitaniumModule.java#L185-L192 clearTimeout(timeoutId); - if (!inited && leading) { - inited = true; - result = func.apply(thisArg, args); + if (maxWait === false) { + if (leading && callCount < 2) { + result = func.apply(thisArg, args); + } } else { + var now = new Date; + if (!maxTimeoutId && !leading) { + lastCalled = now; + } + var remaining = maxWait - (now - lastCalled); + if (remaining <= 0) { + clearTimeout(maxTimeoutId); + maxTimeoutId = null; + lastCalled = now; + result = func.apply(thisArg, args); + } + else if (!maxTimeoutId) { + maxTimeoutId = setTimeout(maxDelayed, remaining); + } + } + if (wait !== maxWait) { timeoutId = setTimeout(delayed, wait); } return result; @@ -4580,7 +4965,8 @@ * passed, it will be used to determine the cache key for storing the result * based on the arguments passed to the memoized function. By default, the first * argument passed to the memoized function is used as the cache key. The `func` - * is executed with the `this` binding of the memoized function. + * is executed with the `this` binding of the memoized function. The result + * cache is exposed as the `cache` property on the memoized function. * * @static * @memberOf _ @@ -4595,13 +4981,16 @@ * }); */ function memoize(func, resolver) { - var cache = {}; - return function() { - var key = keyPrefix + (resolver ? resolver.apply(this, arguments) : arguments[0]); + function memoized() { + var cache = memoized.cache, + key = keyPrefix + (resolver ? resolver.apply(this, arguments) : arguments[0]); + return hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = func.apply(this, arguments)); - }; + } + memoized.cache = {}; + return memoized; } /** @@ -4721,47 +5110,23 @@ * })); */ function throttle(func, wait, options) { - var args, - result, - thisArg, - timeoutId, - lastCalled = 0, - leading = true, + var leading = true, trailing = true; - function trailingCall() { - timeoutId = null; - if (trailing) { - lastCalled = new Date; - result = func.apply(thisArg, args); - } - } if (options === false) { leading = false; - } else if (options && objectTypes[typeof options]) { + } else if (isObject(options)) { leading = 'leading' in options ? options.leading : leading; trailing = 'trailing' in options ? options.trailing : trailing; } - return function() { - var now = new Date; - if (!timeoutId && !leading) { - lastCalled = now; - } - var remaining = wait - (now - lastCalled); - args = arguments; - thisArg = this; + options = getObject(); + options.leading = leading; + options.maxWait = wait; + options.trailing = trailing; - if (remaining <= 0) { - clearTimeout(timeoutId); - timeoutId = null; - lastCalled = now; - result = func.apply(thisArg, args); - } - else if (!timeoutId) { - timeoutId = setTimeout(trailingCall, remaining); - } - return result; - }; + var result = debounce(func, wait, options); + releaseObject(options); + return result; } /** @@ -4814,7 +5179,7 @@ } /** - * This function returns the first argument passed to it. + * This method returns the first argument passed to it. * * @static * @memberOf _ @@ -4863,7 +5228,7 @@ push.apply(args, arguments); var result = func.apply(lodash, args); - return (value && typeof value == 'object' && value == result) + return (value && typeof value == 'object' && value === result) ? this : new lodashWrapper(result); }; @@ -4937,8 +5302,13 @@ if (max == null) { max = min; min = 0; + } else { + max = +max || 0; } - return min + floor(nativeRandom() * ((+max || 0) - min + 1)); + var rand = nativeRandom(); + return (min % 1 || max % 1) + ? min + nativeMin(rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1))), max) + : min + floor(rand * (max - min + 1)); } /** @@ -5341,6 +5711,7 @@ lodash.throttle = throttle; lodash.times = times; lodash.toArray = toArray; + lodash.transform = transform; lodash.union = union; lodash.uniq = uniq; lodash.unzip = unzip; @@ -5365,6 +5736,10 @@ // add functions to `lodash.prototype` mixin(lodash); + // add Underscore compat + lodash.chain = lodash; + lodash.prototype.chain = function() { return this; }; + /*--------------------------------------------------------------------------*/ // add functions that return unwrapped values when chaining @@ -5416,6 +5791,7 @@ lodash.all = every; lodash.any = some; lodash.detect = find; + lodash.findWhere = find; lodash.foldl = reduce; lodash.foldr = reduceRight; lodash.include = contains; @@ -5461,7 +5837,7 @@ * @memberOf _ * @type String */ - lodash.VERSION = '1.2.1'; + lodash.VERSION = '1.3.1'; // add "Chaining" functions to the wrapper lodash.prototype.toString = wrapperToString; @@ -5469,7 +5845,7 @@ lodash.prototype.valueOf = wrapperValueOf; // add `Array` functions that return unwrapped values - each(['join', 'pop', 'shift'], function(methodName) { + basicEach(['join', 'pop', 'shift'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { return func.apply(this.__wrapped__, arguments); @@ -5477,7 +5853,7 @@ }); // add `Array` functions that return the wrapped value - each(['push', 'reverse', 'sort', 'unshift'], function(methodName) { + basicEach(['push', 'reverse', 'sort', 'unshift'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { func.apply(this.__wrapped__, arguments); @@ -5486,7 +5862,7 @@ }); // add `Array` functions that return new wrapped values - each(['concat', 'slice', 'splice'], function(methodName) { + basicEach(['concat', 'slice', 'splice'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { return new lodashWrapper(func.apply(this.__wrapped__, arguments)); @@ -5496,7 +5872,7 @@ // avoid array-like object bugs with `Array#shift` and `Array#splice` // in Firefox < 10 and IE < 9 if (!support.spliceObjects) { - each(['pop', 'shift', 'splice'], function(methodName) { + basicEach(['pop', 'shift', 'splice'], function(methodName) { var func = arrayRef[methodName], isSplice = methodName == 'splice'; @@ -5513,7 +5889,7 @@ } // add pseudo private property to be used and removed during the build process - lodash._each = each; + lodash._basicEach = basicEach; lodash._iteratorTemplate = iteratorTemplate; lodash._shimKeys = shimKeys; diff --git a/dist/restangular.js b/dist/restangular.js index 2cf19a88..a7d02537 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,12 +1,10 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.9 - 2013-07-27 + * @version v1.0.10 - 2013-07-30 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -'use strict'; - (function() { var module = angular.module('restangular', []); diff --git a/dist/restangular.min.js b/dist/restangular.min.js index a10036a5..7bc4208a 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restfull Resources service for AngularJS apps - * @version v1.0.9 - 2013-07-27 + * @version v1.0.10 - 2013-07-30 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -"use strict";!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),""===f||_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return f.useCannonicalId&&(e[f.restangularFields.cannonicalId]=f.getIdFromElem(e)),e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),""===f||_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return f.useCannonicalId&&(e[f.restangularFields.cannonicalId]=f.getIdFromElem(e)),e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 51b465023815da69f20856adc2a94b2d74521593..114e69e6cdb90b6a09547a3cf6937c1338bcbddb 100644 GIT binary patch delta 177 zcmdn`l4sDSZRZ84tP>VE?XAtg;61spBL$nv8J$sD%s`csziu`_Gkdb}7Grr7 XLx2W}gWUond?vSU(PBHZ8N>$w-QPJJ delta 212 zcmbRJl4s0#>ZQf03dJQwnaL&U)?Awd7}?r|K>Dt+3M>lOW?%qeafZn`TO=ojxMAw& uRYK@jvff|Q7lH932W7TdGUAT9tqwLLKa diff --git a/package.json b/package.json index 8fd59232..37be9def 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "restangular", "description": "Restfull Resources service for AngularJS apps", - "version": "1.0.9", + "version": "1.0.10", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", "author": "Martin Gontovnikas ", diff --git a/src/restangular.js b/src/restangular.js index 8803a7df..13b9eca5 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -1,5 +1,3 @@ -'use strict'; - (function() { var module = angular.module('restangular', []); From 1bc6d6592bfb1fdd0d8da2f1813c5974f3d5a7c1 Mon Sep 17 00:00:00 2001 From: Alex Stommes Date: Thu, 1 Aug 2013 16:08:30 -0500 Subject: [PATCH 075/441] When overriding remove set X-HTTP-Method-Override to DELETE --- src/restangular.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/restangular.js b/src/restangular.js index 13b9eca5..522bb9d1 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -702,7 +702,7 @@ module.provider('Restangular', function() { var isOverrideOperation = config.isOverridenMethod(operation); if (isOverrideOperation) { callOperation = 'post'; - callHeaders = _.extend(callHeaders, {'X-HTTP-Method-Override': operation}); + callHeaders = _.extend(callHeaders, {'X-HTTP-Method-Override': operation === 'remove' ? 'DELETE' : operation}); } if (config.isSafe(operation)) { From ee12ad489a83fac9cf95984c663b847ff1a0be18 Mon Sep 17 00:00:00 2001 From: Massimo Cetra Date: Sun, 4 Aug 2013 00:30:02 +0200 Subject: [PATCH 076/441] Documentation addons for the new errorInterceptor features. --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 923846af..1b9263b6 100644 --- a/README.md +++ b/README.md @@ -300,6 +300,11 @@ It must return an object with the following properties: #### errorInterceptor The errorInterceptor is called whenever there's an error. It's a function that receives the response as a parameter. +The errorInterceptor function, whenever it returns `false`, prevents the promise linked to a Restangular request to be executed. +All other return values (besides `false`) are ignored and the promise follows the usual path, eventually reaching the success or error hooks. + +The feature to prevent the promise to complete is usefull whenever you need to intercept each Restangular error response for every request in your AngularJS application in a single place, increasing debugging capabilities and hooking security features in a single place. + #### listTypeIsArray We don't use `$resource` anymore so this property is depracated. I've left it with an empty setter per now to avoid errors, but it'll be removed in the future. From db79ffb0ddff29070e650cfd6d7b74193086af13 Mon Sep 17 00:00:00 2001 From: Aidan Samuel Date: Thu, 8 Aug 2013 15:23:18 +1000 Subject: [PATCH 077/441] tweaks to the documentation --- README.md | 78 ++++++++++++++++++++--------------------- bower.json | 4 +-- dist/restangular.js | 2 +- dist/restangular.min.js | 4 +-- package.json | 4 +-- 5 files changed, 46 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 1b9263b6..19591e02 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,8 @@ -Restangular is an AngularJS service that will help you get, delete and update Restfull Resources with very few lines in the Client side. -This service is a perfect fit for any WebApp that uses Restfull Resources as the API for your application. +Restangular is an AngularJS service that will help you get, delete and update Restful Resources with very few lines in the Client side. +This service is a perfect fit for any WebApp that uses Restful Resources as the API for your application. **If you want to check a live example, [please click this link to plunkr](http://plnkr.co/edit/d6yDka?p=preview).** It's the same example as [Angular's Javascript Projects](http://angularjs.org/#wire-up-a-backend) but Restangularized. @@ -14,9 +14,9 @@ This service is a perfect fit for any WebApp that uses Restfull Resources as the Restangular has several features that distinguish it from $resource: -* **It uses promises**. Instead of doing the "magic" filling of objects like $resource, it uses promises. +* **It uses [promises](http://docs.angularjs.org/api/ng.$q)**. Instead of doing the "magic" filling of objects like $resource, it uses promises. * **You can use this in $routeProvider.resolve**. As Restangular returns promises, you can return any of the methods in the `$routeProvider.resolve` and you'll get the real object injected into your controller if you want. -* **It doesn't have all those `$resource` bugs**. Restangular doesn't have problem with trailling slashes, additional `:` in the URL, escapaing information, expecting only arrays for getting lists, etc. +* **It doesn't have all those `$resource` bugs**. Restangular doesn't have problem with trailling slashes, additional `:` in the URL, escaping information, expecting only arrays for getting lists, etc. * **It supports all HTTP methods**. * **You don't have to create one $resource object per request**. Each time you want to do a request, you can just do it using the object that was returned by Restangular. You don't need to create a new object for this. * **You don't have to write or remember ANY URL**. With $resource, you need to write the URL Template. In here, you don't write any urls. You just write the name of the resource you want to fetch and that's it. @@ -25,7 +25,7 @@ Restangular has several features that distinguish it from $resource: * **Support for wrapped responses**. If your response for a list of element actually returns an object with some property inside which has the list, it's very hard to use $resource. Restangular knows that and it makes it easy on you. Check out https://github.com/mgonto/restangular#my-response-is-actually-wrapped-with-some-metadata-how-do-i-get-the-data-in-that-case * **You can build your own URLs with Restangular objects easily**. Restangular lets you create a Restangular object for any url you want with a really nice builder. -Let's see a quick and short example of this features +Let's see a quick and short example of these features ````javascript // It uses promises. Restangular.one('users').getList().then(function(users) { @@ -90,7 +90,7 @@ angular.module('sample-app').controller('MainCtrl', function($scope, Restangular ## Adding dependency to Restangular module in your app -The first thing you need to do after adding link to script file, is mentioning in your app that you'll use Restangular. +The first thing you need to do after adding the link to your script file, is mentioning in your app that you'll use Restangular. ````javascript var app = angular.module('angularjs-starter', ['restangular']); @@ -102,7 +102,7 @@ Now that you have everything configured, you can just inject this Service to any ### Creating Main Restangular object -There're 2 ways of creating a main Restangular object. +There are 2 ways of creating a main Restangular object. The first one and most common one is by stating the main route of all requests. The second one is by stating the main route and object of all requests. @@ -116,7 +116,7 @@ Restangular.one('accounts', 1234) ### Let's code! -Now that we have our main Object lets's start playing with it. +Now that we have our main Object let's start playing with it. ````javascript // First way of creating a Restangular object. Just saying the base URL @@ -131,7 +131,7 @@ var newAccount = {name: "Gonto's account"}; // POST /accounts baseAccounts.post(newAccount); -//You can do RequestLess "connections" if you need as well +// You can do RequestLess "connections" if you need as well // Just ONE GET to /accounts/123/buildings/456 Restangular.one('accounts', 123).one('buildings', 456).get() @@ -139,7 +139,7 @@ Restangular.one('accounts', 123).one('buildings', 456).get() // Just ONE GET to /accounts/123/buildings Restangular.one('accounts', 123).getList('buildings') -//Here we use Promises then +// Here we use Promises then // GET /accounts baseAccounts.getList().then(function (accounts) { // Here we can continue fetching the tree :). @@ -154,7 +154,7 @@ baseAccounts.getList().then(function (accounts) { // This is a regular JS object, we can change anything we want :) firstAccount.name = "Gonto" - //If we wanted to keep the original as it is, we can copy it to a new element + // If we wanted to keep the original as it is, we can copy it to a new element var editFirstAccount = Restangular.copy(firstAccount); editFirstAccount.name = "New Name"; @@ -218,8 +218,8 @@ account.customPOST("messages", {param: "myParam"}, {}, {name: "My Message"}) ## Configuring Restangular ### Properties -Restangular comes with defaults for all of it's properties but you can configure them. **So, if you don't need to configure something, there's no need to add the configuration.** -You can set all this configurations in **`RestangularProvider` or `Restangular` service to change the global configuration** or you can **use the withConfig method in Restangular service to create a new Restangular service with some scoped configuration**. Check the section on this later. +Restangular comes with defaults for all of its properties but you can configure them. **So, if you don't need to configure something, there's no need to add the configuration.** +You can set all these configurations in **`RestangularProvider` or `Restangular` service to change the global configuration** or you can **use the withConfig method in Restangular service to create a new Restangular service with some scoped configuration**. Check the section on this later. #### baseUrl The base URL for all calls to your API. For example if your URL for fetching accounts is http://example.com/api/v1/accounts, then your baseUrl is `/api/v1`. The default baseUrl is an empty string which resolves to the same url that AngularJS is running, so you can also set an absolute url like `http://api.example.com/api/v1` if you need do set another domain. @@ -228,18 +228,18 @@ The base URL for all calls to your API. For example if your URL for fetching acc This are the fields that you want to save from your parent resources if you need to display them. By default this is an Empty Array which will suit most cases #### parentless -With this property, you can set if you want Restangularized elements to have a parent or not. So, for example if you get an account and then get a nested list of buildings, you may want the buildings URL to be simple `/buildings/123` instead of `/accounts/123/buildings/123`. This configuration lets you do that. +Use this property to control whether Restangularized elements to have a parent or not. So, for example if you get an account and then get a nested list of buildings, you may want the buildings URL to be simple `/buildings/123` instead of `/accounts/123/buildings/123`. This property lets you do that. This method accepts 2 parameters: * Boolean: Specifies if all elements should be parentless or not -* Array: Specified the routes (types) of all elements that should be parentless. For example `['buildings']` +* Array: Specifies the routes (types) of all elements that should be parentless. For example `['buildings']` #### defaultHttpFields `$http` from AngularJS can receive a bunch of parameters like `cache`, `transformRequest` and so on. You can set all of those properties in the object sent on this setter so that they will be used in EVERY API call made by Restangular. This is very useful for caching for example. All properties that can be set can be checked here: http://docs.angularjs.org/api/ng.$http#Parameters #### urlCreator -This is the factory that will create URLs based on the resources. For the time being, only Path UrlCreator is implemented. This means that if you have a resource names Building which is a child of Account, the URL to fetch this will be `/accounts/123/buildings`. In the future, I'll implement more UrlCreator like QueryParams UrlCreator. +This is the factory that will create URLs based on the resources. For the time being, only Path UrlCreator is implemented. This means that if you have a resource named Building which is a child of Account, the URL to fetch this will be `/accounts/123/buildings`. In the future, I'll implement more UrlCreator like QueryParams UrlCreator. #### addElementTransformer This is a hook. After each element has been "restangularized" (Added the new methods from Restangular), the corresponding transformer will be called if it fits. @@ -307,9 +307,9 @@ The feature to prevent the promise to complete is usefull whenever you need to i #### listTypeIsArray -We don't use `$resource` anymore so this property is depracated. I've left it with an empty setter per now to avoid errors, but it'll be removed in the future. +We don't use `$resource` anymore so this property is deprecated. I've left it with an empty setter for now to avoid errors, but it'll be removed in the future. -~~You can set in this property wether the `getList` method will return an Array or not. Most of the times, it will return an array, as it returns a collection of values. However, sometimes this method returns first some metadata and inside it has the array. So this can be used together with `responseExtractor` to get the real array. The default value is true.~~ +~~Use this property to determine whether the `getList` method returns an Array or not. Most of the time it will return an array, as it returns a collection of values. However, sometimes this method returns first some metadata and inside it has the array. So this can be used together with `responseExtractor` to get the real array. The default value is true.~~ #### restangularFields @@ -320,7 +320,7 @@ Restangular required 3 fields for every "Restangularized" element. This are: * parentResource: The reference to the parent resource. Default: parentResource * restangularCollection: A boolean indicating if this is a collection or an element. Default: restangularCollection -All of this fields except for `id` are handled by Restangular, so most of the time you won't change them. You can configure the name of the property that will be binded to all of this fields by setting restangularFields property. +All of these fields except for `id` are handled by Restangular, so most of the time you won't change them. You can configure the name of the property that will be binded to all of this fields by setting restangularFields property. #### methodOverriders @@ -344,7 +344,7 @@ You can set default Headers to be sent with every request. #### requestSuffix -If all of your requests require to send some suffix to work, you can set it here. For example, if you need to send the format like `/users/123.json`you can add that `.json` to the suffix using the `setRequestSuffix`method +If all of your requests require to send some suffix to work, you can set it here. For example, if you need to send the format like `/users/123.json` you can add that `.json` to the suffix using the `setRequestSuffix` method #### useCannonicalId @@ -352,7 +352,7 @@ You can set this to either `true` or `false`. By default it's false. If set to t ### How to configure them globally -You can do this configurations in either the `config` or the `run` method. If your configurations don't need any other services, then I'd recommend you do them in the `config`. If your configurations depend on other services, you can configure them in the `run` using `Restangular` instead of `RestangularProvider` +You can configure this in either the `config` or the `run` method. If your configurations don't need any other services, then I'd recommend you do them in the `config`. If your configurations depend on other services, you can configure them in the `run` using `Restangular` instead of `RestangularProvider` #### Configuring in the `config` ````javascript @@ -371,7 +371,7 @@ app.config(function(RestangularProvider) { RestangularProvider.setDefaultHttpFields({cache: true}); RestangularProvider.setMethodOverriders(["put", "patch"]); - // In this case we are maping the id of each element to the _id field. + // In this case we are mapping the id of each element to the _id field. // We also change the Restangular route. // The default value for parentResource remains the same. RestangularProvider.setRestangularFields({ @@ -420,7 +420,7 @@ app.config(function(RestangularProvider) { RestangularProvider.setRequestSuffix('.json'); }); -//Restangular service that uses Bing +// Restangular service that uses Bing app.factory('BingRestangular', function(Restangular) { return Restangular.withConfig(function(RestangularConfigurer) { RestangularConfigurer.setBaseUrl('http://www.bing.com'); @@ -442,7 +442,7 @@ app.controller('MainCtrl', function(Restangular, BingRestangular) { ## Methods description -There're 3 sets of methods. Collections have some methods and elements have others. There're are also some common methods for all of them +There are 3 sets of methods. Collections have some methods and elements have others. There are are also some common methods for all of them ### Restangular methods This are the methods that can be called in the Restangular object. @@ -491,10 +491,10 @@ This are the methods that can be called in the Restangular object. Let's see an example of this: ````javascript -//GET /accounts/123/messages +// GET /accounts/123/messages Restangular.one("accounts", 123).customGET("messages") -//GET /accounts/messages?param=param2 +// GET /accounts/messages?param=param2 Restangular.all("accounts").customGET("messages", {param: "param2"}) ```` ## Copying elements @@ -506,9 +506,9 @@ Restangular uses enhanced promises when returning. What does this mean? All prom * **call(methodName, params*)**: This will return a new promise of the previous value, after calling the method called methodName with the parameters params. * **get(fieldName)**: This will return a new promise for the type of the field. The param of this new promise is the property `fieldName` from the original promise result. -* **push(object)**: This method will only be in the promises of arrays. It's a sub set of the call method that does a push. +* **push(object)**: This method will only be in the promises of arrays. It's a subset of the call method that does a push. -I know this explanations are quite complicated, so let's see an example :D. +I know these explanations are quite complicated, so let's see an example :D. ````javascript var buildings = Restangular.all("buildings").getList(); @@ -529,7 +529,7 @@ lengthPromise.then(function(length) { ```` ## URL Building -Sometimes, we have a lot of entities names with their ids and we just want to fetch the later entity. In those cases, doing a request for everything to get the last entity is an overkill. For those cases, I've added the possibility to create URLs using the same API as creating a new Restangular object. This connections are created without doing any request. Let's see how to do this: +Sometimes, we have a lot of nested entities (and their IDs), but we just want the last child. In those cases, doing a request for everything to get the last child is overkill. For those cases, I've added the possibility to create URLs using the same API as creating a new Restangular object. This connections are created without making any requests. Let's see how to do this: ````javascript @@ -555,7 +555,7 @@ Let's assume that your API needs some custom methods to work. If that's the case This can be used together with the hook `addElementTransformer` to do some neat stuff. Let's see an example to learn this: ````javascript -//In your app configuration (config method) +// In your app configuration (config method) // It will transform all building elements, NOT collections RestangularProvider.addElementTransformer('buildings', false, function(building) { @@ -579,16 +579,16 @@ RestangularProvider.addElementTransformer('users', true, function(user) { // Then, later in your code you can do the following: -//GET to /buildings/123/evaluate?myParam=param with headers myHeader: value +// GET to /buildings/123/evaluate?myParam=param with headers myHeader: value -//Signature for this "custom created" methods is (params, headers, elem) if it's a safe operation (GET, OPTIONS, etc.) +// Signature for this "custom created" methods is (params, headers, elem) if it's a safe operation (GET, OPTIONS, etc.) // If it's an unsafe operation (POST, PUT, etc.), signature is (elem, params, headers). -// If something is set to any of this variables, the default set in the method creation will be overrided +// If something is set to any of this variables, the default set in the method creation will be overridden // If nothing is set, then the defaults are sent Restangular.one('building', 123).evaluate({myParam: 'param'}); -//GET to /buildings/123/evaluate?myParam=param with headers myHeader: specialHeaderCase +// GET to /buildings/123/evaluate?myParam=param with headers myHeader: specialHeaderCase Restangular.one('building', 123).evaluate({myParam: 'param'}, {'myHeader': 'specialHeaderCase'}); @@ -704,7 +704,7 @@ So, let's assume that your data is the following: } ```` -In this case, you'd need to configure Restangular's `responseExtractor`and `listTypeIsArray`. See the following: +In this case, you'd need to configure Restangular's `responseExtractor` and `listTypeIsArray`. See the following: ````javascript app.config(function(RestangularProvider) { @@ -754,7 +754,7 @@ Restangular.all('users').getList().then(function(users) { userWithId.name = "Gonto"; userWithId.put(); - // ALternatively delete element from list when finished + // Alternatively delete the element from the list when finished userWithId.remove().then(function() { // Updating the list and removing the user after the response is OK. $scope.users = _.without($scope.users, userWithId); @@ -763,7 +763,7 @@ Restangular.all('users').getList().then(function(users) { }); ```` -When you actually get some list by doing +When you actually get a list by doing ````javascript $scope.owners = house.getList('owners') @@ -802,11 +802,11 @@ With these libraries, you always work with immutable stuff, you get compatibilit So, why not use it? If you've never heard of them, by using Restangular, you could start using them. Trust me, you're never going to give them up after this! -# Supported Angular's version +# Supported Angular versions Restangular supports both 1.0.X and 1.1.X up to versions 1.0.7 and 1.1.5. -Also, when using Restangular with version >= 1.1.4, in case you're using Restangular inside a callback not handled by Angular, you've to wrap this all request with a `$scope.apply` to make it work or you need to run one extra `$digest` manually. Check out https://github.com/mgonto/restangular/issues/71 +Also, when using Restangular with version >= 1.1.4, in case you're using Restangular inside a callback not handled by Angular, you have to wrap the whole request with `$scope.apply` to make it work or you need to run one extra `$digest` manually. Check out https://github.com/mgonto/restangular/issues/71 # Server Frameworks diff --git a/bower.json b/bower.json index 4c874d65..8b957119 100644 --- a/bower.json +++ b/bower.json @@ -2,7 +2,7 @@ "name": "restangular", "version": "1.0.10", "main": "./dist/restangular.min.js", - "description": "Restfull Resources service for AngularJS apps", + "description": "Restful Resources service for AngularJS apps", "repository": { "type": "git", "url": "git://github.com/mgonto/restangular.git" @@ -16,4 +16,4 @@ "components", "lib" ] -} \ No newline at end of file +} diff --git a/dist/restangular.js b/dist/restangular.js index a7d02537..35c8fb0e 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,5 +1,5 @@ /** - * Restfull Resources service for AngularJS apps + * Restful Resources service for AngularJS apps * @version v1.0.10 - 2013-07-30 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 7bc4208a..5a1bb6c3 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** - * Restfull Resources service for AngularJS apps + * Restful Resources service for AngularJS apps * @version v1.0.10 - 2013-07-30 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),""===f||_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return f.useCannonicalId&&(e[f.restangularFields.cannonicalId]=f.getIdFromElem(e)),e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),""===f||_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return f.useCannonicalId&&(e[f.restangularFields.cannonicalId]=f.getIdFromElem(e)),e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); diff --git a/package.json b/package.json index 37be9def..091d4866 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "restangular", - "description": "Restfull Resources service for AngularJS apps", + "description": "Restful Resources service for AngularJS apps", "version": "1.0.10", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", @@ -43,4 +43,4 @@ "test": "grunt travis --verbose" }, "license": "MIT" -} \ No newline at end of file +} From 252da22e128c41a3d34374b195f1904643a5710c Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Fri, 9 Aug 2013 11:29:06 -0300 Subject: [PATCH 078/441] 1.0.11 --- CHANGELOG.md | 5 +++++ bower.json | 4 ++-- dist/restangular.js | 14 ++++++++------ dist/restangular.min.js | 4 ++-- dist/restangular.zip | Bin 46235 -> 46395 bytes package.json | 4 ++-- 6 files changed, 19 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d0eeab4..ee7dc920 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +#1.0.11 +* Documentation Typo fixes +* errorInterceptor can now stop Restangular from rejecting the promise +* Bugfix fot method override on DELETE. Now it works + #1.0.9 * **BREAKING CHANGE**: Restangular methods created with `addRestangularMethod` will change its signature depending on the opreation. If the operation is safe (GET, OPTIONS, etc.), the signature is methodName(params, headers, elemForBody). If it's not safe (POST, PUT, etc.), the signature is methodName(elemForBody, params, headers). This is to facilitate using them as when it's not safe, you're usually going to set a body * Now you can configure default request parameters per method and for everything as well diff --git a/bower.json b/bower.json index 8b957119..efe77c1f 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "restangular", - "version": "1.0.10", + "version": "1.0.11", "main": "./dist/restangular.min.js", "description": "Restful Resources service for AngularJS apps", "repository": { @@ -16,4 +16,4 @@ "components", "lib" ] -} +} \ No newline at end of file diff --git a/dist/restangular.js b/dist/restangular.js index 35c8fb0e..0e2e565e 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restful Resources service for AngularJS apps - * @version v1.0.10 - 2013-07-30 + * @version v1.0.11 - 2013-08-09 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT @@ -665,8 +665,9 @@ module.provider('Restangular', function() { resolvePromise(deferred, response, restangularizeCollection(null, processedData, __this[config.restangularFields.route])); } }, function error(response) { - config.errorInterceptor(response); - deferred.reject(response); + if ( config.errorInterceptor(response) !== false ) { + deferred.reject(response); + } }); return restangularizePromise(deferred.promise, true); @@ -700,8 +701,9 @@ module.provider('Restangular', function() { }; var errorCallback = function(response) { - config.errorInterceptor(response); - deferred.reject(response); + if ( config.errorInterceptor(response) !== false ) { + deferred.reject(response); + } }; // Overring HTTP Method var callOperation = operation; @@ -709,7 +711,7 @@ module.provider('Restangular', function() { var isOverrideOperation = config.isOverridenMethod(operation); if (isOverrideOperation) { callOperation = 'post'; - callHeaders = _.extend(callHeaders, {'X-HTTP-Method-Override': operation}); + callHeaders = _.extend(callHeaders, {'X-HTTP-Method-Override': operation === 'remove' ? 'DELETE' : operation}); } if (config.isSafe(operation)) { diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 5a1bb6c3..32339f74 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restful Resources service for AngularJS apps - * @version v1.0.10 - 2013-07-30 + * @version v1.0.11 - 2013-08-09 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),""===f||_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return f.useCannonicalId&&(e[f.restangularFields.cannonicalId]=f.getIdFromElem(e)),e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a),h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a),k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),""===f||_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return f.useCannonicalId&&(e[f.restangularFields.cannonicalId]=f.getIdFromElem(e)),e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a)!==!1&&h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a)!==!1&&k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":"remove"===a?"DELETE":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 114e69e6cdb90b6a09547a3cf6937c1338bcbddb..d6a583a0311258f273a7f8371c9167f041d789ed 100644 GIT binary patch delta 382 zcmbRJl4{ficQ7!NcTBWapFE+%g3nMvSHZ}@ z&{)^NLf61@s+YB4s^Dnp_*_?5AXX{?txvR9f>^q_d0i+g3&_gJcQ)&zh0|oo YEynVg&H;xklsG*(dy5uZ&K3|C05eB)O#lD@ delta 288 zcmdn}ifQ&sCcXe~W)?065ZF-n&uJo`JRgYe=e}b8qn&}_NBcx;^@)j=d1wJ!*s&L6)QIX z>0GG9sIz&=nrDoRI+G`^tJ|!)KA4pSWXj~4E&6CanY?q0u{@>?V825NpUK=?wb;&V G25|udw_|ny diff --git a/package.json b/package.json index 091d4866..a0b17cc9 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "restangular", "description": "Restful Resources service for AngularJS apps", - "version": "1.0.10", + "version": "1.0.11", "filename": "restangular.min.js", "homepage": "https://github.com/mgonto/restangular", "author": "Martin Gontovnikas ", @@ -43,4 +43,4 @@ "test": "grunt travis --verbose" }, "license": "MIT" -} +} \ No newline at end of file From 043415bff08a3bde73573c6fb3f1eea6711e5ccb Mon Sep 17 00:00:00 2001 From: Joe LeBlanc Date: Fri, 9 Aug 2013 14:18:36 -0500 Subject: [PATCH 079/441] Fixed Karma config file --- karma.conf.js | 96 +++++++++++++++++++++++++++------------------------ 1 file changed, 50 insertions(+), 46 deletions(-) diff --git a/karma.conf.js b/karma.conf.js index 65fa7f40..01000d4f 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -1,71 +1,75 @@ // Karma configuration -// Generated on Sun Apr 14 2013 18:31:17 GMT+0200 (CEST) +// Generated on Fri Aug 09 2013 14:14:35 GMT-0500 (CDT) +module.exports = function(config) { + config.set({ -// base path, that will be used to resolve files and exclude -basePath = ''; + // base path, that will be used to resolve files and exclude + basePath: '', + frameworks: ["jasmine"], -// list of files / patterns to load in the browser -files = [ - JASMINE, - JASMINE_ADAPTER, - 'http://code.angularjs.org/1.1.4/angular.js', - 'http://code.angularjs.org/1.1.4/angular-resource.js', - 'http://code.angularjs.org/1.1.4/angular-mocks.js', - 'http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.0/lodash.min.js', - 'src/restangular.js', - 'test/*.js' -]; + // list of files / patterns to load in the browser + files: [ + 'http://code.angularjs.org/1.1.4/angular.js', + 'http://code.angularjs.org/1.1.4/angular-resource.js', + 'http://code.angularjs.org/1.1.4/angular-mocks.js', + 'http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.0/lodash.min.js', + 'src/restangular.js', + 'test/*.js' + ], -// list of files to exclude -exclude = [ - -]; + // list of files to exclude + exclude: [ + ], -// test results reporter to use -// possible values: 'dots', 'progress', 'junit' -reporters = ['progress']; + // test results reporter to use + // possible values: 'dots', 'progress', 'junit' + reporters: ['progress'], -// web server port -port = 9876; + // web server port + port: 9876, -// cli runner port -runnerPort = 9100; + // cli runner port + runnerPort: 9100, -// enable / disable colors in the output (reporters and logs) -colors = true; + // enable / disable colors in the output (reporters and logs) + colors: true, -// level of logging -// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG -logLevel = LOG_INFO; + // level of logging + // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG + logLevel: config.LOG_INFO, -// enable / disable watching file and executing tests whenever any file changes -autoWatch = true; + // enable / disable watching file and executing tests whenever any file changes + autoWatch: true, -// Start these browsers, currently available: -// - Chrome -// - ChromeCanary -// - Firefox -// - Opera -// - Safari (only Mac) -// - PhantomJS -// - IE (only Windows) -browsers = ['PhantomJS']; + // Start these browsers, currently available: + // - Chrome + // - ChromeCanary + // - Firefox + // - Opera + // - Safari (only Mac) + // - PhantomJS + // - IE (only Windows) + browsers: ['PhantomJS'], -// If browser does not capture in given timeout [ms], kill it -captureTimeout = 60000; + // If browser does not capture in given timeout [ms], kill it + captureTimeout: 60000, -// Continuous Integration mode -// if true, it capture browsers, run tests and exit -singleRun = false; + + // Continuous Integration mode + // if true, it capture browsers, run tests and exit + singleRun: false + + }); +}; From b64a7b800545816d8cb6fc2c4d546050caf21715 Mon Sep 17 00:00:00 2001 From: Joe LeBlanc Date: Fri, 9 Aug 2013 15:26:33 -0500 Subject: [PATCH 080/441] Converting over the underscore Karma config --- karma.underscore.conf.js | 96 +++++++++++++++++++++------------------- 1 file changed, 50 insertions(+), 46 deletions(-) diff --git a/karma.underscore.conf.js b/karma.underscore.conf.js index aca20d35..ab1d8240 100644 --- a/karma.underscore.conf.js +++ b/karma.underscore.conf.js @@ -1,71 +1,75 @@ // Karma configuration -// Generated on Sun Apr 14 2013 18:31:17 GMT+0200 (CEST) +// Generated on Fri Aug 09 2013 14:14:35 GMT-0500 (CDT) +module.exports = function(config) { + config.set({ -// base path, that will be used to resolve files and exclude -basePath = ''; + // base path, that will be used to resolve files and exclude + basePath: '', + frameworks: ["jasmine"], -// list of files / patterns to load in the browser -files = [ - JASMINE, - JASMINE_ADAPTER, - 'http://code.angularjs.org/1.1.4/angular.js', - 'http://code.angularjs.org/1.1.4/angular-resource.js', - 'http://code.angularjs.org/1.1.4/angular-mocks.js', - 'http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js', - 'src/restangular.js', - 'test/*.js' -]; + // list of files / patterns to load in the browser + files: [ + 'http://code.angularjs.org/1.1.4/angular.js', + 'http://code.angularjs.org/1.1.4/angular-resource.js', + 'http://code.angularjs.org/1.1.4/angular-mocks.js', + 'http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js', + 'src/restangular.js', + 'test/*.js' + ], -// list of files to exclude -exclude = [ - -]; + // list of files to exclude + exclude: [ + ], -// test results reporter to use -// possible values: 'dots', 'progress', 'junit' -reporters = ['progress']; + // test results reporter to use + // possible values: 'dots', 'progress', 'junit' + reporters: ['progress'], -// web server port -port = 9877; + // web server port + port: 9877, -// cli runner port -runnerPort = 9101; + // cli runner port + runnerPort: 9101, -// enable / disable colors in the output (reporters and logs) -colors = true; + // enable / disable colors in the output (reporters and logs) + colors: true, -// level of logging -// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG -logLevel = LOG_INFO; + // level of logging + // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG + logLevel: config.LOG_INFO, -// enable / disable watching file and executing tests whenever any file changes -autoWatch = true; + // enable / disable watching file and executing tests whenever any file changes + autoWatch: true, -// Start these browsers, currently available: -// - Chrome -// - ChromeCanary -// - Firefox -// - Opera -// - Safari (only Mac) -// - PhantomJS -// - IE (only Windows) -browsers = ['PhantomJS']; + // Start these browsers, currently available: + // - Chrome + // - ChromeCanary + // - Firefox + // - Opera + // - Safari (only Mac) + // - PhantomJS + // - IE (only Windows) + browsers: ['PhantomJS'], -// If browser does not capture in given timeout [ms], kill it -captureTimeout = 60000; + // If browser does not capture in given timeout [ms], kill it + captureTimeout: 60000, -// Continuous Integration mode -// if true, it capture browsers, run tests and exit -singleRun = false; + + // Continuous Integration mode + // if true, it capture browsers, run tests and exit + singleRun: false + + }); +}; From 9a1a8841130182d206b9553ee8dc5c885df5a7ac Mon Sep 17 00:00:00 2001 From: Rob Schley Date: Mon, 12 Aug 2013 11:27:17 -0500 Subject: [PATCH 081/441] Implemented fullResponseInterceptor. --- README.md | 9 +++++++++ src/restangular.js | 13 +++++++++++++ 2 files changed, 22 insertions(+) diff --git a/README.md b/README.md index 19591e02..80318cc8 100644 --- a/README.md +++ b/README.md @@ -279,6 +279,15 @@ The responseInterceptor is called after we get each response from the server. It Some of the use cases of the responseInterceptor are handling wrapped responses and enhancing response elements with more methods among others. +### fullResponseInterceptor +The fullResponseInterceptor is executed after the response data has been restangularized but before the promise is resolved. This allows you to transform the restangularized data based on response headers and intercept promise resolution if necessary. This function receives the following arguments: + +* **data**: The restangularized response data. +* **response**: The response received from the server. +* **deferred**: The deferred promise for the request. + +The fullResponseInterceptor must return the restangularized data element. + #### requestInterceptor The requestInterceptor is called before sending any data to the server. It's a function that must return the element to be requested. This function receives the following arguments: diff --git a/src/restangular.js b/src/restangular.js index f38f3aa0..8517e5ac 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -182,7 +182,16 @@ module.provider('Restangular', function() { config.fullRequestInterceptor = interceptor; }; + /** + * Response interceptor is called just before resolving promises. + */ + config.fullResponseInterceptor = config.fullResponseInterceptor || function(data, response, deferred) { + return data; + }; + object.setFullResponseInterceptor = function(interceptor) { + config.fullResponseInterceptor = interceptor; + }; config.errorInterceptor = config.errorInterceptor || function() {}; @@ -535,6 +544,10 @@ module.provider('Restangular', function() { } function resolvePromise(deferred, response, data) { + + // Trigger the full response interceptor. + data = config.fullResponseInterceptor(data, response, deferred); + if (config.fullResponse) { return deferred.resolve(_.extend(response, { data: data From afa0badf22c30c1d25ed1f6fe303c9d86bdbe6a7 Mon Sep 17 00:00:00 2001 From: Rob Schley Date: Mon, 12 Aug 2013 11:30:06 -0500 Subject: [PATCH 082/441] Updated build based on latest changes. --- dist/dependencies/lodash.js | 216 ++++++++++++++++-------------------- dist/restangular.js | 15 ++- dist/restangular.min.js | 4 +- dist/restangular.zip | Bin 46395 -> 47165 bytes 4 files changed, 112 insertions(+), 123 deletions(-) diff --git a/dist/dependencies/lodash.js b/dist/dependencies/lodash.js index 088c15b9..7dc1deb6 100644 --- a/dist/dependencies/lodash.js +++ b/dist/dependencies/lodash.js @@ -1,6 +1,7 @@ /** * @license - * Lo-Dash 1.3.1 + * Lo-Dash 1.3.1 (Custom Build) + * Build: `lodash -o ./dist/lodash.compat.js` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.4.4 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud Inc. @@ -342,7 +343,6 @@ 'push': null, 'shadowedProps': null, 'string': null, - 'support': null, 'top': '', 'trailing': false, 'true': false, @@ -833,113 +833,96 @@ * @param {Object} data The data object used to populate the text. * @returns {String} Returns the interpolated text. */ - var iteratorTemplate = template( - // the `iterable` may be reassigned by the `top` snippet - 'var index, iterable = <%= firstArg %>, ' + - // assign the `result` variable an initial value - 'result = <%= init %>;\n' + - // exit early if the first argument is falsey - 'if (!iterable) return result;\n' + - // add code before the iteration branches - '<%= top %>;' + - - // array-like iteration: - '<% if (array) { %>\n' + - 'var length = iterable.length; index = -1;\n' + - 'if (<%= array %>) {' + - - // add support for accessing string characters by index if needed - ' <% if (support.unindexedChars) { %>\n' + - ' if (isString(iterable)) {\n' + - " iterable = iterable.split('')\n" + - ' }' + - ' <% } %>\n' + - - // iterate over the array-like value - ' while (++index < length) {\n' + - ' <%= loop %>;\n' + - ' }\n' + - '}\n' + - 'else {' + - - // object iteration: - // add support for iterating over `arguments` objects if needed - ' <% } else if (support.nonEnumArgs) { %>\n' + - ' var length = iterable.length; index = -1;\n' + - ' if (length && isArguments(iterable)) {\n' + - ' while (++index < length) {\n' + - " index += '';\n" + - ' <%= loop %>;\n' + - ' }\n' + - ' } else {' + - ' <% } %>' + - - // avoid iterating over `prototype` properties in older Firefox, Opera, and Safari - ' <% if (support.enumPrototypes) { %>\n' + - " var skipProto = typeof iterable == 'function';\n" + - ' <% } %>' + - - // avoid iterating over `Error.prototype` properties in older IE and Safari - ' <% if (support.enumErrorProps) { %>\n' + - ' var skipErrorProps = iterable === errorProto || iterable instanceof Error;\n' + - ' <% } %>' + - - // define conditions used in the loop - ' <%' + - ' var conditions = [];' + - ' if (support.enumPrototypes) { conditions.push(\'!(skipProto && index == "prototype")\'); }' + - ' if (support.enumErrorProps) { conditions.push(\'!(skipErrorProps && (index == "message" || index == "name"))\'); }' + - ' %>' + - - // iterate own properties using `Object.keys` - ' <% if (useHas && useKeys) { %>\n' + - ' var ownIndex = -1,\n' + - ' ownProps = objectTypes[typeof iterable] && keys(iterable),\n' + - ' length = ownProps ? ownProps.length : 0;\n\n' + - ' while (++ownIndex < length) {\n' + - ' index = ownProps[ownIndex];\n<%' + - " if (conditions.length) { %> if (<%= conditions.join(' && ') %>) {\n <% } %>" + - ' <%= loop %>;' + - ' <% if (conditions.length) { %>\n }<% } %>\n' + - ' }' + - - // else using a for-in loop - ' <% } else { %>\n' + - ' for (index in iterable) {\n<%' + - ' if (useHas) { conditions.push("hasOwnProperty.call(iterable, index)"); }' + - " if (conditions.length) { %> if (<%= conditions.join(' && ') %>) {\n <% } %>" + - ' <%= loop %>;' + - ' <% if (conditions.length) { %>\n }<% } %>\n' + - ' }' + - - // Because IE < 9 can't set the `[[Enumerable]]` attribute of an - // existing property and the `constructor` property of a prototype - // defaults to non-enumerable, Lo-Dash skips the `constructor` - // property when it infers it's iterating over a `prototype` object. - ' <% if (support.nonEnumShadows) { %>\n\n' + - ' if (iterable !== objectProto) {\n' + - " var ctor = iterable.constructor,\n" + - ' isProto = iterable === (ctor && ctor.prototype),\n' + - ' className = iterable === stringProto ? stringClass : iterable === errorProto ? errorClass : toString.call(iterable),\n' + - ' nonEnum = nonEnumProps[className];\n' + - ' <% for (k = 0; k < 7; k++) { %>\n' + - " index = '<%= shadowedProps[k] %>';\n" + - ' if ((!(isProto && nonEnum[index]) && hasOwnProperty.call(iterable, index))<%' + - ' if (!useHas) { %> || (!nonEnum[index] && iterable[index] !== objectProto[index])<% }' + - ' %>) {\n' + - ' <%= loop %>;\n' + - ' }' + - ' <% } %>\n' + - ' }' + - ' <% } %>' + - ' <% } %>' + - ' <% if (array || support.nonEnumArgs) { %>\n}<% } %>\n' + - - // add code to the bottom of the iteration function - '<%= bottom %>;\n' + - // finally, return the `result` - 'return result' - ); + var iteratorTemplate = function(obj) { + + var __p = 'var index, iterable = ' + + (obj.firstArg) + + ', result = ' + + (obj.init) + + ';\nif (!iterable) return result;\n' + + (obj.top) + + ';'; + if (obj.array) { + __p += '\nvar length = iterable.length; index = -1;\nif (' + + (obj.array) + + ') { '; + if (support.unindexedChars) { + __p += '\n if (isString(iterable)) {\n iterable = iterable.split(\'\')\n } '; + } + __p += '\n while (++index < length) {\n ' + + (obj.loop) + + ';\n }\n}\nelse { '; + } else if (support.nonEnumArgs) { + __p += '\n var length = iterable.length; index = -1;\n if (length && isArguments(iterable)) {\n while (++index < length) {\n index += \'\';\n ' + + (obj.loop) + + ';\n }\n } else { '; + } + + if (support.enumPrototypes) { + __p += '\n var skipProto = typeof iterable == \'function\';\n '; + } + + if (support.enumErrorProps) { + __p += '\n var skipErrorProps = iterable === errorProto || iterable instanceof Error;\n '; + } + + var conditions = []; if (support.enumPrototypes) { conditions.push('!(skipProto && index == "prototype")'); } if (support.enumErrorProps) { conditions.push('!(skipErrorProps && (index == "message" || index == "name"))'); } + + if (obj.useHas && obj.useKeys) { + __p += '\n var ownIndex = -1,\n ownProps = objectTypes[typeof iterable] && keys(iterable),\n length = ownProps ? ownProps.length : 0;\n\n while (++ownIndex < length) {\n index = ownProps[ownIndex];\n'; + if (conditions.length) { + __p += ' if (' + + (conditions.join(' && ')) + + ') {\n '; + } + __p += + (obj.loop) + + '; '; + if (conditions.length) { + __p += '\n }'; + } + __p += '\n } '; + } else { + __p += '\n for (index in iterable) {\n'; + if (obj.useHas) { conditions.push("hasOwnProperty.call(iterable, index)"); } if (conditions.length) { + __p += ' if (' + + (conditions.join(' && ')) + + ') {\n '; + } + __p += + (obj.loop) + + '; '; + if (conditions.length) { + __p += '\n }'; + } + __p += '\n } '; + if (support.nonEnumShadows) { + __p += '\n\n if (iterable !== objectProto) {\n var ctor = iterable.constructor,\n isProto = iterable === (ctor && ctor.prototype),\n className = iterable === stringProto ? stringClass : iterable === errorProto ? errorClass : toString.call(iterable),\n nonEnum = nonEnumProps[className];\n '; + for (k = 0; k < 7; k++) { + __p += '\n index = \'' + + (obj.shadowedProps[k]) + + '\';\n if ((!(isProto && nonEnum[index]) && hasOwnProperty.call(iterable, index))'; + if (!obj.useHas) { + __p += ' || (!nonEnum[index] && iterable[index] !== objectProto[index])'; + } + __p += ') {\n ' + + (obj.loop) + + ';\n } '; + } + __p += '\n } '; + } + + } + + if (obj.array || support.nonEnumArgs) { + __p += '\n}'; + } + __p += + (obj.bottom) + + ';\nreturn result'; + + return __p + }; /** Reusable iterator options for `assign` and `defaults` */ var defaultsIteratorOptions = { @@ -1048,8 +1031,6 @@ // data properties data.shadowedProps = shadowedProps; - data.support = support; - // iterator options data.array = data.bottom = data.loop = data.top = ''; data.init = 'iterable'; @@ -5431,11 +5412,11 @@ text || (text = ''); // avoid missing dependencies when `iteratorTemplate` is not defined - options = iteratorTemplate ? defaults({}, options, settings) : settings; + options = defaults({}, options, settings); - var imports = iteratorTemplate && defaults({}, options.imports, settings.imports), - importsKeys = iteratorTemplate ? keys(imports) : ['_'], - importsValues = iteratorTemplate ? values(imports) : [lodash]; + var imports = defaults({}, options.imports, settings.imports), + importsKeys = keys(imports), + importsValues = values(imports); var isEvaluating, index = 0, @@ -5888,11 +5869,6 @@ }); } - // add pseudo private property to be used and removed during the build process - lodash._basicEach = basicEach; - lodash._iteratorTemplate = iteratorTemplate; - lodash._shimKeys = shimKeys; - return lodash; } diff --git a/dist/restangular.js b/dist/restangular.js index 0e2e565e..ccb72d33 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restful Resources service for AngularJS apps - * @version v1.0.11 - 2013-08-09 + * @version v1.0.11 - 2013-08-12 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT @@ -189,7 +189,16 @@ module.provider('Restangular', function() { config.fullRequestInterceptor = interceptor; }; + /** + * Response interceptor is called just before resolving promises. + */ + config.fullResponseInterceptor = config.fullResponseInterceptor || function(data, response, deferred) { + return data; + }; + object.setFullResponseInterceptor = function(interceptor) { + config.fullResponseInterceptor = interceptor; + }; config.errorInterceptor = config.errorInterceptor || function() {}; @@ -542,6 +551,10 @@ module.provider('Restangular', function() { } function resolvePromise(deferred, response, data) { + + // Trigger the full response interceptor. + data = config.fullResponseInterceptor(data, response, deferred); + if (config.fullResponse) { return deferred.resolve(_.extend(response, { data: data diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 32339f74..e549c90f 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restful Resources service for AngularJS apps - * @version v1.0.11 - 2013-08-09 + * @version v1.0.11 - 2013-08-12 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),""===f||_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return f.useCannonicalId&&(e[f.restangularFields.cannonicalId]=f.getIdFromElem(e)),e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a)!==!1&&h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a)!==!1&&k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":"remove"===a?"DELETE":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.fullResponseInterceptor=b.fullResponseInterceptor||function(a){return a},a.setFullResponseInterceptor=function(a){b.fullResponseInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),""===f||_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return c=f.fullResponseInterceptor(c,b,a),f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return f.useCannonicalId&&(e[f.restangularFields.cannonicalId]=f.getIdFromElem(e)),e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a)!==!1&&h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a)!==!1&&k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":"remove"===a?"DELETE":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index d6a583a0311258f273a7f8371c9167f041d789ed..457c19a0a174e0fef15acab1972d15696cdbcae1 100644 GIT binary patch delta 571 zcmdn}ifQi$Cf)#VW)?065ZDpTGm%$;4@fzuEqNSsw2Oh^XxBvRY$ijajVr8VCpYj4 za|ERp7v$#^r%u+B5|_y;EiO?=N=?fzN>wOIEzZv=%gjqxC@9L$%`BcAsIESFf)v~2 zeR^z@XG=+gXnoJTlGLK))Pj=yB88e7g|yPV%P7d5`g-nDK^tcqz0LUH%TZPFR^@LTB+=|P6DU&}M3xlkj{6CU= zvqJDzQz1~`y-|O)UO|U}0ffaFCi85SoYWZv48(~mR&4&$`I$=%8IIyhB83CV7tM>N^;wuATpin+!7 delta 189 zcmdn{fob{ficQ7!NcTBX-W-_qcxWY Date: Wed, 14 Aug 2013 14:23:21 -0300 Subject: [PATCH 083/441] Added getter for defaultHeaders Now you can access them via Restangular.defaultHeaders Fixes #233 --- dist/dependencies/angular.js | 13533 ++++++++++++++++++++------------- dist/dependencies/lodash.js | 216 +- dist/restangular.js | 6 +- dist/restangular.min.js | 4 +- dist/restangular.zip | Bin 47165 -> 47247 bytes package.json | 2 +- src/restangular.js | 4 +- 7 files changed, 8424 insertions(+), 5341 deletions(-) diff --git a/dist/dependencies/angular.js b/dist/dependencies/angular.js index a860c859..140682e4 100644 --- a/dist/dependencies/angular.js +++ b/dist/dependencies/angular.js @@ -1,13 +1,78 @@ /** - * @license AngularJS v1.0.7 + * @license AngularJS v1.2.0rc1 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ -(function(window, document, undefined) { -'use strict'; +(function(window, document, undefined) {'use strict'; + +/** + * @description + * + * This object provides a utility for producing rich Error messages within + * Angular. It can be called as follows: + * + * var exampleMinErr = minErr('example'); + * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); + * + * The above creates an instance of minErr in the example namespace. The + * resulting error will have a namespaced error code of example.one. The + * resulting error will replace {0} with the value of foo, and {1} with the + * value of bar. The object is not restricted in the number of arguments it can + * take. + * + * If fewer arguments are specified than necessary for interpolation, the extra + * interpolation markers will be preserved in the final string. + * + * Since data will be parsed statically during a build step, some restrictions + * are applied with respect to how minErr instances are created and called. + * Instances should have names of the form namespaceMinErr for a minErr created + * using minErr('namespace') . Error codes, namespaces and template strings + * should all be static strings, not variables or general expressions. + * + * @param {string} module The namespace to use for the new minErr instance. + * @returns {function(string, string, ...): Error} instance + */ + +function minErr(module) { + return function () { + var prefix = '[' + (module ? module + ':' : '') + arguments[0] + '] ', + template = arguments[1], + templateArgs = arguments, + message; + + message = prefix + template.replace(/\{\d+\}/g, function (match) { + var index = +match.slice(1, -1), arg; + + if (index + 2 < templateArgs.length) { + arg = templateArgs[index + 2]; + if (isFunction(arg)) { + return arg.toString().replace(/ ?\{[\s\S]*$/, ''); + } else if (isUndefined(arg)) { + return 'undefined'; + } else if (!isString(arg)) { + return toJson(arg); + } + return arg; + } + return match; + }); + + return new Error(message); + }; +} //////////////////////////////////// +/** + * hasOwnProperty may be overwritten by a property of the same name, or entirely + * absent from an object that does not inherit Object.prototype; this copy is + * used instead + */ +var hasOwnPropertyFn = Object.prototype.hasOwnProperty; +var hasOwnPropertyLocal = function(obj, key) { + return hasOwnPropertyFn.call(obj, key); +}; + /** * @ngdoc function * @name angular.lowercase @@ -60,35 +125,36 @@ var /** holds major version number for IE or NaN for real browsers */ slice = [].slice, push = [].push, toString = Object.prototype.toString, + ngMinErr = minErr('ng'), + + _angular = window.angular, /** @name angular */ angular = window.angular || (window.angular = {}), angularModule, nodeName_, uid = ['0', '0', '0']; - /** * @private * @param {*} obj * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, ...) */ function isArrayLike(obj) { - if (!obj || (typeof obj.length !== 'number')) return false; + if (obj == null || isWindow(obj)) { + return false; + } + + var length = obj.length; - // We have on object which has length property. Should we treat it as array? - if (typeof obj.hasOwnProperty != 'function' && - typeof obj.constructor != 'function') { - // This is here for IE8: it is a bogus object treat it as array; + if (obj.nodeType === 1 && length) { return true; - } else { - return obj instanceof JQLite || // JQLite - (jQuery && obj instanceof jQuery) || // jQuery - toString.call(obj) !== '[object Object]' || // some browser native object - typeof obj.callee === 'function'; // arguments (on IE8 looks like regular obj) } -} + return isArray(obj) || !isFunction(obj) && ( + length === 0 || typeof length === "number" && length > 0 && (length - 1) in obj + ); +} /** * @ngdoc function @@ -203,7 +269,7 @@ function nextUid() { /** * Set or clear the hashkey for an object. - * @param obj object + * @param obj object * @param h the hashkey (!truthy to delete the hashkey) */ function setHashKey(obj, h) { @@ -251,7 +317,6 @@ function inherit(parent, extra) { return extend(new (extend(function() {}, {prototype:parent}))(), extra); } - /** * @ngdoc function * @name angular.noop @@ -282,7 +347,7 @@ noop.$inject = []; *
      function transformer(transformationFn, value) {
-       return (transformationFn || identity)(value);
+       return (transformationFn || angular.identity)(value);
      };
    
*/ @@ -409,6 +474,18 @@ function isArray(value) { function isFunction(value){return typeof value == 'function';} +/** + * Determines if a value is a regular expression object. + * + * @private + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is a `RegExp`. + */ +function isRegExp(value) { + return toString.apply(value) == '[object RegExp]'; +} + + /** * Checks if `obj` is a window object. * @@ -436,9 +513,20 @@ function isBoolean(value) { } -function trim(value) { - return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; -} +var trim = (function() { + // native trim is way faster: http://jsperf.com/angular-trim-test + // but IE doesn't have it... :-( + // TODO: we should move this into IE/ES5 polyfill + if (!String.prototype.trim) { + return function(value) { + return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; + }; + } + return function(value) { + return isString(value) ? value.trim() : value; + }; +})(); + /** * @ngdoc function @@ -454,7 +542,7 @@ function trim(value) { function isElement(node) { return node && (node.nodeName // we are a direct element - || (node.bind && node.find)); // we have a bind and find method part of jQuery API + || (node.on && node.find)); // we have an on and find method part of jQuery API } /** @@ -573,7 +661,10 @@ function isLeafNode (node) { * @returns {*} The copy or updated `destination`, if `destination` was specified. */ function copy(source, destination){ - if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope"); + if (isWindow(source) || isScope(source)) { + throw ngMinErr('cpws', "Can't copy! Making copies of Window or Scope instances is not supported."); + } + if (!destination) { destination = source; if (source) { @@ -581,12 +672,14 @@ function copy(source, destination){ destination = copy(source, []); } else if (isDate(source)) { destination = new Date(source.getTime()); + } else if (isRegExp(source)) { + destination = new RegExp(source.source); } else if (isObject(source)) { destination = copy(source, {}); } } } else { - if (source === destination) throw Error("Can't copy equivalent objects or arrays"); + if (source === destination) throw ngMinErr('cpi', "Can't copy! Source and destination are identical."); if (isArray(source)) { destination.length = 0; for ( var i = 0; i < source.length; i++) { @@ -628,7 +721,7 @@ function shallowCopy(src, dst) { * @function * * @description - * Determines if two objects or two values are equivalent. Supports value types, arrays and + * Determines if two objects or two values are equivalent. Supports value types, regular expressions, arrays and * objects. * * Two objects or values are considered equivalent if at least one of the following is true: @@ -636,8 +729,11 @@ function shallowCopy(src, dst) { * * Both objects or values pass `===` comparison. * * Both objects or values are of the same type and all of their properties pass `===` comparison. * * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal) + * * Both values represent the same regular expression (In JavasScript, + * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual + * representation matches). * - * During a property comparision, properties of `function` type and properties with names + * During a property comparison, properties of `function` type and properties with names * that begin with `$` are ignored. * * Scope and DOMWindow objects are being compared only by identify (`===`). @@ -654,6 +750,7 @@ function equals(o1, o2) { if (t1 == t2) { if (t1 == 'object') { if (isArray(o1)) { + if (!isArray(o2)) return false; if ((length = o1.length) == o2.length) { for(key=0; key @@ -825,10 +943,19 @@ function startingTag(element) { function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; forEach((keyValue || "").split('&'), function(keyValue){ - if (keyValue) { + if ( keyValue ) { key_value = keyValue.split('='); - key = decodeURIComponent(key_value[0]); - obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true; + key = tryDecodeURIComponent(key_value[0]); + if ( isDefined(key) ) { + var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; + if (!obj[key]) { + obj[key] = val; + } else if(isArray(obj[key])) { + obj[key].push(val); + } else { + obj[key] = [obj[key],val]; + } + } } }); return obj; @@ -837,14 +964,20 @@ function parseKeyValue(/**string*/keyValue) { function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { + if (isArray(value)) { + forEach(value, function(arrayValue) { + parts.push(encodeUriQuery(key, true) + (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true))); + }); + } else { parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true))); + } }); return parts.length ? parts.join('&') : ''; } /** - * We need our custom method because encodeURIComponent is too agressive and doesn't follow + * We need our custom method because encodeURIComponent is too aggressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar @@ -864,7 +997,7 @@ function encodeUriSegment(val) { /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom - * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be + * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" @@ -894,10 +1027,14 @@ function encodeUriQuery(val, pctEncodeSpaces) { * @description * * Use this directive to auto-bootstrap an application. Only - * one directive can be used per HTML document. The directive + * one ngApp directive can be used per HTML document. The directive * designates the root of the application and is typically placed * at the root of the page. * + * The first ngApp found in the document will be auto-bootstrapped. To use multiple applications in an + * HTML document you must manually bootstrap them using {@link angular.bootstrap}. + * Applications cannot be nested. + * * In the example below if the `ngApp` directive would not be placed * on the `html` element then the document would not be compiled * and the `{{ 1+2 }}` would not be resolved to `3`. @@ -963,25 +1100,35 @@ function angularInit(element, bootstrap) { * * See: {@link guide/bootstrap Bootstrap} * + * Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually. + * They must use {@link api/ng.directive:ngApp ngApp}. + * * @param {Element} element DOM element which is the root of angular application. * @param {Array=} modules an array of module declarations. See: {@link angular.module modules} * @returns {AUTO.$injector} Returns the newly created injector for this app. */ function bootstrap(element, modules) { - var resumeBootstrapInternal = function() { + var doBootstrap = function() { element = jqLite(element); + + if (element.injector()) { + var tag = (element[0] === document) ? 'document' : startingTag(element); + throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag); + } + modules = modules || []; modules.unshift(['$provide', function($provide) { $provide.value('$rootElement', element); }]); modules.unshift('ng'); var injector = createInjector(modules); - injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', - function(scope, element, compile, injector) { + injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate', + function(scope, element, compile, injector, animate) { scope.$apply(function() { element.data('$injector', injector); compile(element)(scope); }); + animate.enabled(true); }] ); return injector; @@ -990,7 +1137,7 @@ function bootstrap(element, modules) { var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { - return resumeBootstrapInternal(); + return doBootstrap(); } window.name = window.name.replace(NG_DEFER_BOOTSTRAP, ''); @@ -998,7 +1145,7 @@ function bootstrap(element, modules) { forEach(extraModules, function(module) { modules.push(module); }); - resumeBootstrapInternal(); + doBootstrap(); }; } @@ -1022,9 +1169,10 @@ function bindJQuery() { injector: JQLitePrototype.injector, inheritedData: JQLitePrototype.inheritedData }); - JQLitePatchJQueryRemove('remove', true); - JQLitePatchJQueryRemove('empty'); - JQLitePatchJQueryRemove('html'); + // Method signature: JQLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) + JQLitePatchJQueryRemove('remove', true, true, false); + JQLitePatchJQueryRemove('empty', false, false, false); + JQLitePatchJQueryRemove('html', false, false, true); } else { jqLite = JQLite; } @@ -1036,7 +1184,7 @@ function bindJQuery() { */ function assertArg(arg, name, reason) { if (!arg) { - throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required")); + throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required")); } return arg; } @@ -1051,6 +1199,33 @@ function assertArgFn(arg, name, acceptArrayAnnotation) { return arg; } +/** + * Return the value accessible from the object by path. Any undefined traversals are ignored + * @param {Object} obj starting object + * @param {string} path path to traverse + * @param {boolean=true} bindFnToScope + * @returns value as accessible by path + */ +//TODO(misko): this function needs to be removed +function getter(obj, path, bindFnToScope) { + if (!path) return obj; + var keys = path.split('.'); + var key; + var lastInstance = obj; + var len = keys.length; + + for (var i = 0; i < len; i++) { + key = keys[i]; + if (obj) { + obj = (lastInstance = obj)[key]; + } + } + if (!bindFnToScope && isFunction(obj)) { + return bind(lastInstance, obj); + } + return obj; +} + /** * @ngdoc interface * @name angular.Module @@ -1081,8 +1256,8 @@ function setupModuleLoader(window) { * * # Module * - * A module is a collocation of services, directives, filters, and configuration information. Module - * is used to configure the {@link AUTO.$injector $injector}. + * A module is a collection of services, directives, filters, and configuration information. + * `angular.module` is used to configure the {@link AUTO.$injector $injector}. * *
      * // Create a new module
@@ -1121,7 +1296,9 @@ function setupModuleLoader(window) {
       }
       return ensure(modules, name, function() {
         if (!requires) {
-          throw Error('No module: ' + name);
+          throw minErr('$injector')('nomod', "Module '{0}' is not available! You either misspelled the module name " +
+              "or forgot to load it. If registering a module ensure that you specify the dependencies as the second " +
+              "argument.", name);
         }
 
         /** @type {!Array.>} */
@@ -1214,6 +1391,39 @@ function setupModuleLoader(window) {
            */
           constant: invokeLater('$provide', 'constant', 'unshift'),
 
+          /**
+           * @ngdoc method
+           * @name angular.Module#animation
+           * @methodOf angular.Module
+           * @param {string} name animation name
+           * @param {Function} animationFactory Factory function for creating new instance of an animation.
+           * @description
+           *
+           * **NOTE**: animations are take effect only if the **ngAnimate** module is loaded.
+           *
+           *
+           * Defines an animation hook that can be later used with {@link ngAnimate.$animate $animate} service and
+           * directives that use this service.
+           *
+           * 
+           * module.animation('.animation-name', function($inject1, $inject2) {
+           *   return {
+           *     eventName : function(element, done) {
+           *       //code to run the animation
+           *       //once complete, then run done()
+           *       return function cancellationFunction(element) {
+           *         //code to cancel the animation
+           *       }
+           *     }
+           *   }
+           * })
+           * 
+ * + * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and + * {@link ngAnimate ngAnimate module} for more information. + */ + animation: invokeLater('$animateProvider', 'register'), + /** * @ngdoc method * @name angular.Module#filter @@ -1313,11 +1523,11 @@ function setupModuleLoader(window) { * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { - full: '1.0.7', // all of these placeholder strings will be replaced by grunt's + full: '1.2.0rc1', // all of these placeholder strings will be replaced by grunt's major: 1, // package task - minor: 0, - dot: 7, - codeName: 'monochromatic-rainbow' + minor: 2, + dot: 0, + codeName: 'spooky-giraffe' }; @@ -1343,6 +1553,7 @@ function publishExternalAPI(angular){ 'isNumber': isNumber, 'isElement': isElement, 'isArray': isArray, + '$$minErr': minErr, 'version': version, 'isDate': isDate, 'lowercase': lowercase, @@ -1370,7 +1581,7 @@ function publishExternalAPI(angular){ style: styleDirective, option: optionDirective, ngBind: ngBindDirective, - ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective, + ngBindHtml: ngBindHtmlDirective, ngBindTemplate: ngBindTemplateDirective, ngClass: ngClassDirective, ngClassEven: ngClassEvenDirective, @@ -1380,19 +1591,18 @@ function publishExternalAPI(angular){ ngController: ngControllerDirective, ngForm: ngFormDirective, ngHide: ngHideDirective, + ngIf: ngIfDirective, ngInclude: ngIncludeDirective, ngInit: ngInitDirective, ngNonBindable: ngNonBindableDirective, ngPluralize: ngPluralizeDirective, ngRepeat: ngRepeatDirective, ngShow: ngShowDirective, - ngSubmit: ngSubmitDirective, ngStyle: ngStyleDirective, ngSwitch: ngSwitchDirective, ngSwitchWhen: ngSwitchWhenDirective, ngSwitchDefault: ngSwitchDefaultDirective, ngOptions: ngOptionsDirective, - ngView: ngViewDirective, ngTransclude: ngTranscludeDirective, ngModel: ngModelDirective, ngList: ngListDirective, @@ -1405,6 +1615,7 @@ function publishExternalAPI(angular){ directive(ngEventDirectives); $provide.provider({ $anchorScroll: $AnchorScrollProvider, + $animate: $AnimateProvider, $browser: $BrowserProvider, $cacheFactory: $CacheFactoryProvider, $controller: $ControllerProvider, @@ -1417,14 +1628,15 @@ function publishExternalAPI(angular){ $location: $LocationProvider, $log: $LogProvider, $parse: $ParseProvider, - $route: $RouteProvider, - $routeParams: $RouteParamsProvider, $rootScope: $RootScopeProvider, $q: $QProvider, + $sce: $SceProvider, + $sceDelegate: $SceDelegateProvider, $sniffer: $SnifferProvider, $templateCache: $TemplateCacheProvider, $timeout: $TimeoutProvider, - $window: $WindowProvider + $window: $WindowProvider, + $$urlUtils: $$UrlUtilsProvider }); } ]); @@ -1456,13 +1668,14 @@ function publishExternalAPI(angular){ * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never * raw DOM references. * - * ## Angular's jQuery lite provides the following methods: + * ## Angular's jqLite + * Angular's lite version of jQuery provides only the following jQuery methods: * * - [addClass()](http://api.jquery.com/addClass/) * - [after()](http://api.jquery.com/after/) * - [append()](http://api.jquery.com/append/) * - [attr()](http://api.jquery.com/attr/) - * - [bind()](http://api.jquery.com/bind/) - Does not support namespaces + * - [bind()](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData * - [children()](http://api.jquery.com/children/) - Does not support selectors * - [clone()](http://api.jquery.com/clone/) * - [contents()](http://api.jquery.com/contents/) @@ -1473,6 +1686,8 @@ function publishExternalAPI(angular){ * - [hasClass()](http://api.jquery.com/hasClass/) * - [html()](http://api.jquery.com/html/) * - [next()](http://api.jquery.com/next/) - Does not support selectors + * - [on()](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData + * - [off()](http://api.jquery.com/off/) - Does not support namespaces or selectors * - [parent()](http://api.jquery.com/parent/) - Does not support selectors * - [prepend()](http://api.jquery.com/prepend/) * - [prop()](http://api.jquery.com/prop/) @@ -1484,13 +1699,19 @@ function publishExternalAPI(angular){ * - [replaceWith()](http://api.jquery.com/replaceWith/) * - [text()](http://api.jquery.com/text/) * - [toggleClass()](http://api.jquery.com/toggleClass/) - * - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Doesn't pass native event objects to handlers. - * - [unbind()](http://api.jquery.com/unbind/) - Does not support namespaces + * - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers. + * - [unbind()](http://api.jquery.com/off/) - Does not support namespaces * - [val()](http://api.jquery.com/val/) * - [wrap()](http://api.jquery.com/wrap/) * - * ## In addtion to the above, Angular provides additional methods to both jQuery and jQuery lite: + * ## jQuery/jqLite Extras + * Angular also provides the following additional methods and events to both jQuery and jqLite: * + * ### Events + * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event + * on all DOM nodes being removed. This can be used to clean up and 3rd party bindings to the DOM + * element before it is removed. + * ### Methods * - `controller(name)` - retrieves the controller of the current element or its parent. By default * retrieves controller associated with the `ngController` directive. If `name` is provided as * camelCase directive name, then the controller for this directive will be retrieved (e.g. @@ -1520,6 +1741,7 @@ function jqNextId() { return ++jqId; } var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; var MOZ_HACK_REGEXP = /^moz([A-Z])/; +var jqLiteMinErr = minErr('jqLite'); /** * Converts snake_case to camelCase. @@ -1537,37 +1759,38 @@ function camelCase(name) { ///////////////////////////////////////////// // jQuery mutation patch // -// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a +// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a // $destroy event on all DOM nodes being removed. // ///////////////////////////////////////////// -function JQLitePatchJQueryRemove(name, dispatchThis) { +function JQLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) { var originalJqFn = jQuery.fn[name]; originalJqFn = originalJqFn.$original || originalJqFn; removePatch.$original = originalJqFn; jQuery.fn[name] = removePatch; - function removePatch() { - var list = [this], + function removePatch(param) { + var list = filterElems && param ? [this.filter(param)] : [this], fireEvent = dispatchThis, set, setIndex, setLength, - element, childIndex, childLength, children, - fns, events; - - while(list.length) { - set = list.shift(); - for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { - element = jqLite(set[setIndex]); - if (fireEvent) { - element.triggerHandler('$destroy'); - } else { - fireEvent = !fireEvent; - } - for(childIndex = 0, childLength = (children = element.children()).length; - childIndex < childLength; - childIndex++) { - list.push(jQuery(children[childIndex])); + element, childIndex, childLength, children; + + if (!getterIfNoArguments || param != null) { + while(list.length) { + set = list.shift(); + for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { + element = jqLite(set[setIndex]); + if (fireEvent) { + element.triggerHandler('$destroy'); + } else { + fireEvent = !fireEvent; + } + for(childIndex = 0, childLength = (children = element.children()).length; + childIndex < childLength; + childIndex++) { + list.push(jQuery(children[childIndex])); + } } } } @@ -1582,7 +1805,7 @@ function JQLite(element) { } if (!(this instanceof JQLite)) { if (isString(element) && element.charAt(0) != '<') { - throw Error('selectors not implemented'); + throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element'); } return new JQLite(element); } @@ -1594,7 +1817,8 @@ function JQLite(element) { div.innerHTML = '
 
' + element; // IE insanity to make NoScope elements work! div.removeChild(div.firstChild); // remove the superfluous div JQLiteAddNodes(this, div.childNodes); - this.remove(); // detach the elements from the temporary DOM div. + var fragment = jqLite(document.createDocumentFragment()); + fragment.append(this); // detach the elements from the temporary DOM div. } else { JQLiteAddNodes(this, element); } @@ -1611,7 +1835,9 @@ function JQLiteDealoc(element){ } } -function JQLiteUnbind(element, type, fn) { +function JQLiteOff(element, type, fn, unsupported) { + if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument'); + var events = JQLiteExpandoStore(element, 'events'), handle = JQLiteExpandoStore(element, 'handle'); @@ -1623,23 +1849,30 @@ function JQLiteUnbind(element, type, fn) { delete events[type]; }); } else { - if (isUndefined(fn)) { - removeEventListenerFn(element, type, events[type]); - delete events[type]; - } else { - arrayRemove(events[type], fn); - } + forEach(type.split(' '), function(type) { + if (isUndefined(fn)) { + removeEventListenerFn(element, type, events[type]); + delete events[type]; + } else { + arrayRemove(events[type] || [], fn); + } + }); } } -function JQLiteRemoveData(element) { +function JQLiteRemoveData(element, name) { var expandoId = element[jqName], expandoStore = jqCache[expandoId]; if (expandoStore) { + if (name) { + delete jqCache[expandoId].data[name]; + return; + } + if (expandoStore.handle) { expandoStore.events.$destroy && expandoStore.handle({}, '$destroy'); - JQLiteUnbind(element); + JQLiteOff(element); } delete jqCache[expandoId]; element[jqName] = undefined; // ie does not allow deletion of attributes on elements. @@ -1739,7 +1972,7 @@ function JQLiteInheritedData(element, name, value) { } while (element.length) { - if (value = element.data(name)) return value; + if ((value = element.data(name)) !== undefined) return value; element = element.parent(); } } @@ -1757,9 +1990,14 @@ var JQLitePrototype = JQLite.prototype = { fn(); } - this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9 - // we can not use jqLite since we are not done loading and jQuery could be loaded later. - JQLite(window).bind('load', trigger); // fallback to window.onload for others + // check if document already is loaded + if (document.readyState === 'complete'){ + setTimeout(trigger); + } else { + this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9 + // we can not use jqLite since we are not done loading and jQuery could be loaded later. + JQLite(window).on('load', trigger); // fallback to window.onload for others + } }, toString: function() { var value = []; @@ -1783,11 +2021,11 @@ var JQLitePrototype = JQLite.prototype = { // value on get. ////////////////////////////////////////// var BOOLEAN_ATTR = {}; -forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), function(value) { +forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) { BOOLEAN_ATTR[lowercase(value)] = value; }); var BOOLEAN_ELEMENTS = {}; -forEach('input,select,option,textarea,button,form'.split(','), function(value) { +forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { BOOLEAN_ELEMENTS[uppercase(value)] = true; }); @@ -1880,27 +2118,38 @@ forEach({ } }, - text: extend((msie < 9) - ? function(element, value) { - if (element.nodeType == 1 /** Element */) { - if (isUndefined(value)) - return element.innerText; - element.innerText = value; - } else { - if (isUndefined(value)) - return element.nodeValue; - element.nodeValue = value; - } + text: (function() { + var NODE_TYPE_TEXT_PROPERTY = []; + if (msie < 9) { + NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/ + NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/ + } else { + NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/ + NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/ + } + getText.$dv = ''; + return getText; + + function getText(element, value) { + var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType] + if (isUndefined(value)) { + return textProp ? element[textProp] : ''; } - : function(element, value) { - if (isUndefined(value)) { - return element.textContent; - } - element.textContent = value; - }, {$dv:''}), + element[textProp] = value; + } + })(), val: function(element, value) { if (isUndefined(value)) { + if (nodeName_(element) === 'SELECT' && element.multiple) { + var result = []; + forEach(element.options, function (option) { + if (option.selected) { + result.push(option.value || option.text); + } + }); + return result.length === 0 ? null : result; + } return element.value; } element.value = value; @@ -1942,8 +2191,14 @@ forEach({ return this; } else { // we are a read, so read the first child. - if (this.length) - return fn(this[0], arg1, arg2); + var value = fn.$dv; + // Only if we have $dv do we iterate over all, otherwise it is just the first element. + var jj = value == undefined ? Math.min(this.length, 1) : this.length; + for (var j = 0; j < jj; j++) { + var nodeValue = fn(this[j], arg1, arg2); + value = value ? value + nodeValue : nodeValue; + } + return value; } } else { // we are a write, so apply to all children @@ -1953,7 +2208,6 @@ forEach({ // return self for chaining return this; } - return fn.$dv; }; }); @@ -1985,7 +2239,7 @@ function createEventHandler(element, events) { } event.isDefaultPrevented = function() { - return event.defaultPrevented; + return event.defaultPrevented || event.returnValue == false; }; forEach(events[type || event.type], function(fn) { @@ -2020,7 +2274,9 @@ forEach({ dealoc: JQLiteDealoc, - bind: function bindFn(element, type, fn){ + on: function onFn(element, type, fn, unsupported){ + if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters'); + var events = JQLiteExpandoStore(element, 'events'), handle = JQLiteExpandoStore(element, 'handle'); @@ -2051,22 +2307,22 @@ forEach({ } } return false; - }; + }; events[type] = []; - - // Refer to jQuery's implementation of mouseenter & mouseleave + + // Refer to jQuery's implementation of mouseenter & mouseleave // Read about mouseenter and mouseleave: // http://www.quirksmode.org/js/events_mouse.html#link8 - var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"} - bindFn(element, eventmap[type], function(event) { - var ret, target = this, related = event.relatedTarget; + var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"}; + + onFn(element, eventmap[type], function(event) { + var target = this, related = event.relatedTarget; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !contains(target, related)) ){ handle(event, type); - } - + } }); } else { @@ -2079,7 +2335,7 @@ forEach({ }); }, - unbind: JQLiteUnbind, + off: JQLiteOff, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; @@ -2109,8 +2365,9 @@ forEach({ append: function(element, node) { forEach(new JQLite(node), function(child){ - if (element.nodeType === 1) + if (element.nodeType === 1 || element.nodeType === 11) { element.appendChild(child); + } }); }, @@ -2118,12 +2375,7 @@ forEach({ if (element.nodeType === 1) { var index = element.firstChild; forEach(new JQLite(node), function(child){ - if (index) { - element.insertBefore(child, index); - } else { - element.appendChild(child); - index = child; - } + element.insertBefore(child, index); }); } }, @@ -2185,32 +2437,40 @@ forEach({ clone: JQLiteClone, - triggerHandler: function(element, eventName) { + triggerHandler: function(element, eventName, eventData) { var eventFns = (JQLiteExpandoStore(element, 'events') || {})[eventName]; + eventData = eventData || { + preventDefault: noop, + stopPropagation: noop + }; forEach(eventFns, function(fn) { - fn.call(element, null); + fn.call(element, eventData); }); } }, function(fn, name){ /** * chaining functions */ - JQLite.prototype[name] = function(arg1, arg2) { + JQLite.prototype[name] = function(arg1, arg2, arg3) { var value; for(var i=0; i < this.length; i++) { if (value == undefined) { - value = fn(this[i], arg1, arg2); + value = fn(this[i], arg1, arg2, arg3); if (value !== undefined) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { - JQLiteAddNodes(value, fn(this[i], arg1, arg2)); + JQLiteAddNodes(value, fn(this[i], arg1, arg2, arg3)); } } return value == undefined ? this : value; }; + + // bind legacy bind/unbind to on/off + JQLite.prototype.bind = JQLite.prototype.on; + JQLite.prototype.unbind = JQLite.prototype.off; }); /** @@ -2278,50 +2538,6 @@ HashMap.prototype = { } }; -/** - * A map where multiple values can be added to the same key such that they form a queue. - * @returns {HashQueueMap} - */ -function HashQueueMap() {} -HashQueueMap.prototype = { - /** - * Same as array push, but using an array as the value for the hash - */ - push: function(key, value) { - var array = this[key = hashKey(key)]; - if (!array) { - this[key] = [value]; - } else { - array.push(value); - } - }, - - /** - * Same as array shift, but using an array as the value for the hash - */ - shift: function(key) { - var array = this[key = hashKey(key)]; - if (array) { - if (array.length == 1) { - delete this[key]; - return array[0]; - } else { - return array.shift(); - } - } - }, - - /** - * return the first item without deleting it - */ - peek: function(key) { - var array = this[hashKey(key)]; - if (array) { - return array[0]; - } - } -}; - /** * @ngdoc function * @name angular.injector @@ -2364,6 +2580,7 @@ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; +var $injectorMinErr = minErr('$injector'); function annotate(fn) { var $inject, fnText, @@ -2473,6 +2690,18 @@ function annotate(fn) { * @returns {*} the value returned by the invoked `fn` function. */ +/** + * @ngdoc method + * @name AUTO.$injector#has + * @methodOf AUTO.$injector + * + * @description + * Allows the user to query if the particular service exist. + * + * @param {string} Name of the service to query. + * @returns {boolean} returns true if injector has given service. + */ + /** * @ngdoc method * @name AUTO.$injector#instantiate @@ -2511,7 +2740,7 @@ function annotate(fn) { * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); *
* - * This method does not work with code minfication / obfuscation. For this reason the following annotation strategies + * This method does not work with code minification / obfuscation. For this reason the following annotation strategies * are supported. * * # The `$inject` property @@ -2730,9 +2959,10 @@ function createInjector(modulesToLoad) { decorator: decorator } }, - providerInjector = createInternalInjector(providerCache, function() { - throw Error("Unknown provider: " + path.join(' <- ')); - }), + providerInjector = (providerCache.$injector = + createInternalInjector(providerCache, function() { + throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); + })), instanceCache = {}, instanceInjector = (instanceCache.$injector = createInternalInjector(instanceCache, function(servicename) { @@ -2764,7 +2994,7 @@ function createInjector(modulesToLoad) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { - throw Error('Provider ' + name + ' must define $get factory method.'); + throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); } return providerCache[name + providerSuffix] = provider_; } @@ -2802,39 +3032,36 @@ function createInjector(modulesToLoad) { forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; loadedModules.put(module, true); - if (isString(module)) { - var moduleFn = angularModule(module); - runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); - try { + try { + if (isString(module)) { + var moduleFn = angularModule(module); + runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); + for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { var invokeArgs = invokeQueue[i], - provider = invokeArgs[0] == '$injector' - ? providerInjector - : providerInjector.get(invokeArgs[0]); + provider = providerInjector.get(invokeArgs[0]); provider[invokeArgs[1]].apply(provider, invokeArgs[2]); } - } catch (e) { - if (e.message) e.message += ' from ' + module; - throw e; + } else if (isFunction(module)) { + runBlocks.push(providerInjector.invoke(module)); + } else if (isArray(module)) { + runBlocks.push(providerInjector.invoke(module)); + } else { + assertArgFn(module, 'module'); } - } else if (isFunction(module)) { - try { - runBlocks.push(providerInjector.invoke(module)); - } catch (e) { - if (e.message) e.message += ' from ' + module; - throw e; + } catch (e) { + if (isArray(module)) { + module = module[module.length - 1]; } - } else if (isArray(module)) { - try { - runBlocks.push(providerInjector.invoke(module)); - } catch (e) { - if (e.message) e.message += ' from ' + String(module[module.length - 1]); - throw e; + if (e.message && e.stack && e.stack.indexOf(e.message) == -1) { + // Safari & FF's stack traces don't contain error.message content unlike those of Chrome and IE + // So if stack doesn't contain message, we create a new string that contains both. + // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. + e = e.message + '\n' + e.stack; } - } else { - assertArgFn(module, 'module'); + throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", module, e.stack || e.message || e); } }); return runBlocks; @@ -2847,12 +3074,9 @@ function createInjector(modulesToLoad) { function createInternalInjector(cache, factory) { function getService(serviceName) { - if (typeof serviceName !== 'string') { - throw Error('Service name expected'); - } if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { - throw Error('Circular dependency: ' + path.join(' <- ')); + throw $injectorMinErr('cdep', 'Circular dependency found: {0}', path.join(' <- ')); } return cache[serviceName]; } else { @@ -2874,6 +3098,9 @@ function createInjector(modulesToLoad) { for(i = 0, length = $inject.length; i < length; i++) { key = $inject[i]; + if (typeof key !== 'string') { + throw $injectorMinErr('itkn', 'Incorrect injection token! Expected service name as string, got {0}', key); + } args.push( locals && locals.hasOwnProperty(key) ? locals[key] @@ -2920,7 +3147,10 @@ function createInjector(modulesToLoad) { invoke: invoke, instantiate: instantiate, get: getService, - annotate: annotate + annotate: annotate, + has: function(name) { + return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); + } }; } } @@ -2992,76 +3222,262 @@ function $AnchorScrollProvider() { }]; } +var $animateMinErr = minErr('$animate'); + /** - * ! This is a private undocumented service ! + * @ngdoc object + * @name ng.$animateProvider * - * @name ng.$browser - * @requires $log * @description - * This object has two goals: + * Default implementation of $animate that doesn't perform any animations, instead just synchronously performs DOM + * updates and calls done() callbacks. * - * - hide all the global state in the browser caused by the window object - * - abstract away all the browser specific features and inconsistencies + * In order to enable animations the ngAnimate module has to be loaded. * - * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` - * service, which can be used for convenient testing of the application without the interaction with - * the real browser apis. - */ -/** - * @param {object} window The global window object. - * @param {object} document jQuery wrapped document. - * @param {function()} XHR XMLHttpRequest constructor. - * @param {object} $log console.log or an object with the same interface. - * @param {object} $sniffer $sniffer service + * To see the functional implementation check out src/ngAnimate/animate.js */ -function Browser(window, document, $log, $sniffer) { - var self = this, - rawDocument = document[0], - location = window.location, - history = window.history, - setTimeout = window.setTimeout, - clearTimeout = window.clearTimeout, - pendingDeferIds = {}; - - self.isMock = false; +var $AnimateProvider = ['$provide', function($provide) { - var outstandingRequestCount = 0; - var outstandingRequestCallbacks = []; + this.$$selectors = {}; - // TODO(vojta): remove this temporary api - self.$$completeOutstandingRequest = completeOutstandingRequest; - self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; /** - * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` - * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. + * @ngdoc function + * @name ng.$animateProvider#register + * @methodOf ng.$animateProvider + * + * @description + * Registers a new injectable animation factory function. The factory function produces the animation object which + * contains callback functions for each event that is expected to be animated. + * + * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction` must be called once the + * element animation is complete. If a function is returned then the animation service will use this function to + * cancel the animation whenever a cancel event is triggered. + * + * + *
+   *   return {
+     *     eventFn : function(element, done) {
+     *       //code to run the animation
+     *       //once complete, then run done()
+     *       return function cancellationFunction() {
+     *         //code to cancel the animation
+     *       }
+     *     }
+     *   }
+   *
+ * + * @param {string} name The name of the animation. + * @param {function} factory The factory function that will be executed to return the animation object. */ - function completeOutstandingRequest(fn) { - try { - fn.apply(null, sliceArgs(arguments, 1)); - } finally { - outstandingRequestCount--; - if (outstandingRequestCount === 0) { - while(outstandingRequestCallbacks.length) { - try { - outstandingRequestCallbacks.pop()(); - } catch (e) { - $log.error(e); - } - } - } - } - } + this.register = function(name, factory) { + var key = name + '-animation'; + if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel', + "Expecting class selector starting with '.' got '{0}'.", name); + this.$$selectors[name.substr(1)] = key; + $provide.factory(key, factory); + }; - /** - * @private - * Note: this method is used only by scenario runner - * TODO(vojta): prefix this method with $$ ? - * @param {function()} callback Function that will be called when no outstanding request - */ - self.notifyWhenNoOutstandingRequests = function(callback) { - // force browser to execute all pollFns - this is needed so that cookies and other pollers fire - // at some deterministic time in respect to the test runner's actions. Leaving things up to the + this.$get = ['$timeout', function($timeout) { + + /** + * @ngdoc object + * @name ng.$animate + * + * @description + * The $animate service provides rudimentary DOM manipulation functions to insert, remove, move elements within + * the DOM as well as adding and removing classes. This service is the core service used by the ngAnimate $animator + * service which provides high-level animation hooks for CSS and JavaScript. + * + * $animate is available in the AngularJS core, however, the ngAnimate module must be included to enable full out + * animation support. Otherwise, $animate will only perform simple DOM manipulation operations. + * + * To learn more about enabling animation support, click here to visit the {@link ngAnimate ngAnimate module page} + * as well as the {@link ngAnimate.$animate ngAnimate $animate service page}. + */ + return { + + /** + * @ngdoc function + * @name ng.$animate#enter + * @methodOf ng.$animate + * @function + * + * @description + * Inserts the element into the DOM either after the `after` element or within the `parent` element. Once complete, + * the done() callback will be fired (if provided). + * + * @param {jQuery/jqLite element} element the element which will be inserted into the DOM + * @param {jQuery/jqLite element} parent the parent element which will append the element as a child (if the after element is not present) + * @param {jQuery/jqLite element} after the sibling element which will append the element after itself + * @param {function=} done callback function that will be called after the element has been inserted into the DOM + */ + enter : function(element, parent, after, done) { + var afterNode = after && after[after.length - 1]; + var parentNode = parent && parent[0] || afterNode && afterNode.parentNode; + // IE does not like undefined so we have to pass null. + var afterNextSibling = (afterNode && afterNode.nextSibling) || null; + forEach(element, function(node) { + parentNode.insertBefore(node, afterNextSibling); + }); + $timeout(done || noop, 0, false); + }, + + /** + * @ngdoc function + * @name ng.$animate#leave + * @methodOf ng.$animate + * @function + * + * @description + * Removes the element from the DOM. Once complete, the done() callback will be fired (if provided). + * + * @param {jQuery/jqLite element} element the element which will be removed from the DOM + * @param {function=} done callback function that will be called after the element has been removed from the DOM + */ + leave : function(element, done) { + element.remove(); + $timeout(done || noop, 0, false); + }, + + /** + * @ngdoc function + * @name ng.$animate#move + * @methodOf ng.$animate + * @function + * + * @description + * Moves the position of the provided element within the DOM to be placed either after the `after` element or inside of the `parent` element. + * Once complete, the done() callback will be fired (if provided). + * + * @param {jQuery/jqLite element} element the element which will be moved around within the DOM + * @param {jQuery/jqLite element} parent the parent element where the element will be inserted into (if the after element is not present) + * @param {jQuery/jqLite element} after the sibling element where the element will be positioned next to + * @param {function=} done the callback function (if provided) that will be fired after the element has been moved to it's new position + */ + move : function(element, parent, after, done) { + // Do not remove element before insert. Removing will cause data associated with the + // element to be dropped. Insert will implicitly do the remove. + this.enter(element, parent, after, done); + }, + + /** + * @ngdoc function + * @name ng.$animate#addClass + * @methodOf ng.$animate + * @function + * + * @description + * Adds the provided className CSS class value to the provided element. Once complete, the done() callback will be fired (if provided). + * + * @param {jQuery/jqLite element} element the element which will have the className value added to it + * @param {string} className the CSS class which will be added to the element + * @param {function=} done the callback function (if provided) that will be fired after the className value has been added to the element + */ + addClass : function(element, className, done) { + className = isString(className) ? + className : + isArray(className) ? className.join(' ') : ''; + element.addClass(className); + $timeout(done || noop, 0, false); + }, + + /** + * @ngdoc function + * @name ng.$animate#removeClass + * @methodOf ng.$animate + * @function + * + * @description + * Removes the provided className CSS class value from the provided element. Once complete, the done() callback will be fired (if provided). + * + * @param {jQuery/jqLite element} element the element which will have the className value removed from it + * @param {string} className the CSS class which will be removed from the element + * @param {function=} done the callback function (if provided) that will be fired after the className value has been removed from the element + */ + removeClass : function(element, className, done) { + className = isString(className) ? + className : + isArray(className) ? className.join(' ') : ''; + element.removeClass(className); + $timeout(done || noop, 0, false); + }, + + enabled : noop + }; + }]; +}]; + +/** + * ! This is a private undocumented service ! + * + * @name ng.$browser + * @requires $log + * @description + * This object has two goals: + * + * - hide all the global state in the browser caused by the window object + * - abstract away all the browser specific features and inconsistencies + * + * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` + * service, which can be used for convenient testing of the application without the interaction with + * the real browser apis. + */ +/** + * @param {object} window The global window object. + * @param {object} document jQuery wrapped document. + * @param {function()} XHR XMLHttpRequest constructor. + * @param {object} $log console.log or an object with the same interface. + * @param {object} $sniffer $sniffer service + */ +function Browser(window, document, $log, $sniffer) { + var self = this, + rawDocument = document[0], + location = window.location, + history = window.history, + setTimeout = window.setTimeout, + clearTimeout = window.clearTimeout, + pendingDeferIds = {}; + + self.isMock = false; + + var outstandingRequestCount = 0; + var outstandingRequestCallbacks = []; + + // TODO(vojta): remove this temporary api + self.$$completeOutstandingRequest = completeOutstandingRequest; + self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; + + /** + * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` + * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. + */ + function completeOutstandingRequest(fn) { + try { + fn.apply(null, sliceArgs(arguments, 1)); + } finally { + outstandingRequestCount--; + if (outstandingRequestCount === 0) { + while(outstandingRequestCallbacks.length) { + try { + outstandingRequestCallbacks.pop()(); + } catch (e) { + $log.error(e); + } + } + } + } + } + + /** + * @private + * Note: this method is used only by scenario runner + * TODO(vojta): prefix this method with $$ ? + * @param {function()} callback Function that will be called when no outstanding request + */ + self.notifyWhenNoOutstandingRequests = function(callback) { + // force browser to execute all pollFns - this is needed so that cookies and other pollers fire + // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach(pollFns, function(pollFn){ pollFn(); }); @@ -3116,7 +3532,8 @@ function Browser(window, document, $log, $sniffer) { ////////////////////////////////////////////////////////////// var lastBrowserUrl = location.href, - baseElement = document.find('base'); + baseElement = document.find('base'), + replacedUrl = null; /** * @name ng.$browser#url @@ -3151,14 +3568,21 @@ function Browser(window, document, $log, $sniffer) { baseElement.attr('href', baseElement.attr('href')); } } else { - if (replace) location.replace(url); - else location.href = url; + if (replace) { + location.replace(url); + replacedUrl = url; + } else { + location.href = url; + replacedUrl = null; + } } return self; // getter } else { - // the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 - return location.href.replace(/%27/g,"'"); + // - the replacedUrl is a workaround for an IE8-9 issue with location.replace method that doesn't update + // location.href synchronously + // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 + return replacedUrl || location.href.replace(/%27/g,"'"); } }; @@ -3204,9 +3628,9 @@ function Browser(window, document, $log, $sniffer) { // changed by push/replaceState // html5 history api - popstate event - if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange); + if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange); // hashchange event - if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange); + if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange); // polling else self.addPollFn(fireUrlChange); @@ -3244,7 +3668,7 @@ function Browser(window, document, $log, $sniffer) { * @methodOf ng.$browser * * @param {string=} name Cookie name - * @param {string=} value Cokkie value + * @param {string=} value Cookie value * * @description * The cookies method provides a 'private' low level access to browser cookies. @@ -3307,12 +3731,12 @@ function Browser(window, document, $log, $sniffer) { /** * @name ng.$browser#defer * @methodOf ng.$browser - * @param {function()} fn A function, who's execution should be defered. + * @param {function()} fn A function, who's execution should be deferred. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description - * Executes a fn asynchroniously via `setTimeout(fn, delay)`. + * Executes a fn asynchronously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed @@ -3336,10 +3760,10 @@ function Browser(window, document, $log, $sniffer) { * @methodOf ng.$browser.defer * * @description - * Cancels a defered task identified with `deferId`. + * Cancels a deferred task identified with `deferId`. * * @param {*} deferId Token returned by the `$browser.defer` function. - * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled. + * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully canceled. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { @@ -3365,7 +3789,20 @@ function $BrowserProvider(){ * @name ng.$cacheFactory * * @description - * Factory that constructs cache objects. + * Factory that constructs cache objects and gives access to them. + * + *
+ * 
+ *  var cache = $cacheFactory('cacheId');
+ *  expect($cacheFactory.get('cacheId')).toBe(cache);
+ *  expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
+ *
+ *  cache.put("key", "value");
+ *  cache.put("another key", "another value");
+ * 
+ *  expect(cache.info()).toEqual({id: 'cacheId', size: 2}); // Since we've specified no options on creation
+ * 
+ * 
* * * @param {string} cacheId Name or id of the newly created cache. @@ -3376,7 +3813,7 @@ function $BrowserProvider(){ * @returns {object} Newly created cache object with the following set of methods: * * - `{object}` `info()` — Returns id, size, and options of cache. - * - `{void}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache. + * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns it. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache. * - `{void}` `removeAll()` — Removes all cached values. @@ -3390,7 +3827,7 @@ function $CacheFactoryProvider() { function cacheFactory(cacheId, options) { if (cacheId in caches) { - throw Error('cacheId ' + cacheId + ' taken'); + throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId); } var size = 0, @@ -3415,6 +3852,8 @@ function $CacheFactoryProvider() { if (size > capacity) { this.remove(staleEnd.key); } + + return value; }, @@ -3497,6 +3936,16 @@ function $CacheFactoryProvider() { } + /** + * @ngdoc method + * @name ng.$cacheFactory#info + * @methodOf ng.$cacheFactory + * + * @description + * Get information about all the of the caches that have been created + * + * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info` + */ cacheFactory.info = function() { var info = {}; forEach(caches, function(cache, cacheId) { @@ -3506,6 +3955,17 @@ function $CacheFactoryProvider() { }; + /** + * @ngdoc method + * @name ng.$cacheFactory#get + * @methodOf ng.$cacheFactory + * + * @description + * Get access to a cache object by the `cacheId` used when it was created. + * + * @param {string} cacheId Name or id of a cache to access. + * @returns {object} Cache object identified by the cacheId or undefined if no such cache. + */ cacheFactory.get = function(cacheId) { return caches[cacheId]; }; @@ -3520,8 +3980,44 @@ function $CacheFactoryProvider() { * @name ng.$templateCache * * @description - * Cache used for storing html templates. - * + * The first time a template is used, it is loaded in the template cache for quick retrieval. You can + * load templates directly into the cache in a `script` tag, or by consuming the `$templateCache` + * service directly. + * + * Adding via the `script` tag: + *
+ * 
+ * 
+ * 
+ * 
+ *   ...
+ * 
+ * 
+ * + * **Note:** the `script` tag containing the template does not need to be included in the `head` of the document, but + * it must be below the `ng-app` definition. + * + * Adding via the $templateCache service: + * + *
+ * var myApp = angular.module('myApp', []);
+ * myApp.run(function($templateCache) {
+ *   $templateCache.put('templateId.html', 'This is the content of the template');
+ * });
+ * 
+ * + * To retrieve the template later, simply use it in your HTML: + *
+ * 
+ *
+ * + * or get it via Javascript: + *
+ * $templateCache.get('templateId.html')
+ * 
+ * * See {@link ng.$cacheFactory $cacheFactory}. * */ @@ -3549,9 +4045,6 @@ function $TemplateCacheProvider() { */ -var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: '; - - /** * @ngdoc function * @name ng.$compile @@ -3672,6 +4165,7 @@ var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: '; * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. */ +var $compileMinErr = minErr('$compile'); /** * @ngdoc service @@ -3686,9 +4180,13 @@ function $CompileProvider($provide) { Suffix = 'Directive', COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/, - MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ', - urlSanitizationWhitelist = /^\s*(https?|ftp|mailto|file):/; + aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|file):/, + imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//; + // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes + // The assumption is that future DOM event attribute names will begin with + // 'on' and be composed of only English letters. + var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]*|formaction)$/; /** * @ngdoc function @@ -3697,17 +4195,17 @@ function $CompileProvider($provide) { * @function * * @description - * Register a new directives with the compiler. + * Register a new directive with the compiler. * * @param {string} name Name of the directive in camel-case. (ie ngBind which will match as * ng-bind). - * @param {function} directiveFactory An injectable directive factroy function. See {@link guide/directive} for more + * @param {function|Array} directiveFactory An injectable directive factory function. See {@link guide/directive} for more * info. * @returns {ng.$compileProvider} Self for chaining. */ this.directive = function registerDirective(name, directiveFactory) { if (isString(name)) { - assertArg(directiveFactory, 'directive'); + assertArg(directiveFactory, 'directiveFactory'); if (!hasDirectives.hasOwnProperty(name)) { hasDirectives[name] = []; $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', @@ -3743,7 +4241,7 @@ function $CompileProvider($provide) { /** * @ngdoc function - * @name ng.$compileProvider#urlSanitizationWhitelist + * @name ng.$compileProvider#aHrefSanitizationWhitelist * @methodOf ng.$compileProvider * @function * @@ -3753,29 +4251,59 @@ function $CompileProvider($provide) { * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * - * Any url about to be assigned to a[href] via data-binding is first normalized and turned into an - * absolute url. Afterwards the url is matched against the `urlSanitizationWhitelist` regular - * expression. If a match is found the original url is written into the dom. Otherwise the - * absolute url is prefixed with `'unsafe:'` string and only then it is written into the DOM. + * Any url about to be assigned to a[href] via data-binding is first normalized and turned into + * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` + * regular expression. If a match is found, the original url is written into the dom. Otherwise, + * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. + * + * @param {RegExp=} regexp New regexp to whitelist urls with. + * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for + * chaining otherwise. + */ + this.aHrefSanitizationWhitelist = function(regexp) { + if (isDefined(regexp)) { + aHrefSanitizationWhitelist = regexp; + return this; + } + return aHrefSanitizationWhitelist; + }; + + + /** + * @ngdoc function + * @name ng.$compileProvider#imgSrcSanitizationWhitelist + * @methodOf ng.$compileProvider + * @function + * + * @description + * Retrieves or overrides the default regular expression that is used for whitelisting of safe + * urls during img[src] sanitization. + * + * The sanitization is a security measure aimed at prevent XSS attacks via html links. + * + * Any url about to be assigned to img[src] via data-binding is first normalized and turned into an + * absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` regular + * expression. If a match is found, the original url is written into the dom. Otherwise, the + * absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ - this.urlSanitizationWhitelist = function(regexp) { + this.imgSrcSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { - urlSanitizationWhitelist = regexp; + imgSrcSanitizationWhitelist = regexp; return this; } - return urlSanitizationWhitelist; + return imgSrcSanitizationWhitelist; }; this.$get = [ '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', - '$controller', '$rootScope', '$document', + '$controller', '$rootScope', '$document', '$sce', '$$urlUtils', '$animate', function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, - $controller, $rootScope, $document) { + $controller, $rootScope, $document, $sce, $$urlUtils, $animate) { var Attributes = function(element, attr) { this.$$element = element; @@ -3786,6 +4314,42 @@ function $CompileProvider($provide) { $normalize: directiveNormalize, + /** + * @ngdoc function + * @name ng.$compile.directive.Attributes#$addClass + * @methodOf ng.$compile.directive.Attributes + * @function + * + * @description + * Adds the CSS class value specified by the classVal parameter to the element. If animations + * are enabled then an animation will be triggered for the class addition. + * + * @param {string} classVal The className value that will be added to the element + */ + $addClass : function(classVal) { + if(classVal && classVal.length > 0) { + $animate.addClass(this.$$element, classVal); + } + }, + + /** + * @ngdoc function + * @name ng.$compile.directive.Attributes#$removeClass + * @methodOf ng.$compile.directive.Attributes + * @function + * + * @description + * Removes the CSS class value specified by the classVal parameter from the element. If animations + * are enabled then an animation will be triggered for the class removal. + * + * @param {string} classVal The className value that will be removed from the element + */ + $removeClass : function(classVal) { + if(classVal && classVal.length > 0) { + $animate.removeClass(this.$$element, classVal); + } + }, + /** * Set a normalized attribute on the element in a way such that all directives * can share the attribute. This function properly handles boolean attributes. @@ -3796,49 +4360,64 @@ function $CompileProvider($provide) { * @param {string=} attrName Optional none normalized name. Defaults to key. */ $set: function(key, value, writeAttr, attrName) { - var booleanKey = getBooleanAttrName(this.$$element[0], key), - $$observers = this.$$observers, - normalizedVal; - - if (booleanKey) { - this.$$element.prop(key, value); - attrName = booleanKey; - } - - this[key] = value; - - // translate normalized key to actual key - if (attrName) { - this.$attr[key] = attrName; + //special case for class attribute addition + removal + //so that class changes can tap into the animation + //hooks provided by the $animate service + if(key == 'class') { + value = value || ''; + var current = this.$$element.attr('class') || ''; + this.$removeClass(tokenDifference(current, value).join(' ')); + this.$addClass(tokenDifference(value, current).join(' ')); } else { - attrName = this.$attr[key]; - if (!attrName) { - this.$attr[key] = attrName = snake_case(key, '-'); - } - } + var booleanKey = getBooleanAttrName(this.$$element[0], key), + normalizedVal, + nodeName; + if (booleanKey) { + this.$$element.prop(key, value); + attrName = booleanKey; + } - // sanitize a[href] values - if (nodeName_(this.$$element[0]) === 'A' && key === 'href') { - urlSanitizationNode.setAttribute('href', value); + this[key] = value; - // href property always returns normalized absolute url, so we can match against that - normalizedVal = urlSanitizationNode.href; - if (!normalizedVal.match(urlSanitizationWhitelist)) { - this[key] = value = 'unsafe:' + normalizedVal; + // translate normalized key to actual key + if (attrName) { + this.$attr[key] = attrName; + } else { + attrName = this.$attr[key]; + if (!attrName) { + this.$attr[key] = attrName = snake_case(key, '-'); + } } - } + nodeName = nodeName_(this.$$element); + + // sanitize a[href] and img[src] values + if ((nodeName === 'A' && key === 'href') || + (nodeName === 'IMG' && key === 'src')) { + // NOTE: $$urlUtils.resolve() doesn't support IE < 8 so we don't sanitize for that case. + if (!msie || msie >= 8 ) { + normalizedVal = $$urlUtils.resolve(value); + if (normalizedVal !== '') { + if ((key === 'href' && !normalizedVal.match(aHrefSanitizationWhitelist)) || + (key === 'src' && !normalizedVal.match(imgSrcSanitizationWhitelist))) { + this[key] = value = 'unsafe:' + normalizedVal; + } + } + } + } - if (writeAttr !== false) { - if (value === null || value === undefined) { - this.$$element.removeAttr(attrName); - } else { - this.$$element.attr(attrName, value); + if (writeAttr !== false) { + if (value === null || value === undefined) { + this.$$element.removeAttr(attrName); + } else { + this.$$element.attr(attrName, value); + } } } // fire observers + var $$observers = this.$$observers; $$observers && forEach($$observers[key], function(fn) { try { fn(value); @@ -3846,6 +4425,22 @@ function $CompileProvider($provide) { $exceptionHandler(e); } }); + + function tokenDifference(str1, str2) { + var values = [], + tokens1 = str1.split(/\s+/), + tokens2 = str2.split(/\s+/); + + outer: + for(var i=0;i forEach($compileNodes, function(node, index){ if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) { - $compileNodes[index] = jqLite(node).wrap('').parent()[0]; + $compileNodes[index] = node = jqLite(node).wrap('').parent()[0]; } }); - var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority); + var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority, ignoreDirective); return function publicLinkFn(scope, cloneConnectFn){ assertArg(scope, 'scope'); // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart @@ -3922,10 +4518,6 @@ function $CompileProvider($provide) { }; } - function wrongMode(localName, mode) { - throw Error("Unsupported '" + mode + "' for '" + localName + "'."); - } - function safeAddClass($element, className) { try { $element.addClass(className); @@ -3950,7 +4542,7 @@ function $CompileProvider($provide) { * @param {number=} max directive priority * @returns {?function} A composite linking function of all of the matched directives or null. */ - function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority) { + function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective) { var linkFns = [], nodeLinkFn, childLinkFn, directives, attrs, linkFnFound; @@ -3958,7 +4550,7 @@ function $CompileProvider($provide) { attrs = new Attributes(); // we must always refer to nodeList[i] since the nodes can be replaced underneath us. - directives = collectDirectives(nodeList[i], [], attrs, maxPriority); + directives = collectDirectives(nodeList[i], [], attrs, i == 0 ? maxPriority : undefined, ignoreDirective); nodeLinkFn = (directives.length) ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement) @@ -4007,7 +4599,7 @@ function $CompileProvider($provide) { transcludeScope.$$transcluded = true; return transcludeFn(transcludeScope, cloneFn). - bind('$destroy', bind(transcludeScope, transcludeScope.$destroy)); + on('$destroy', bind(transcludeScope, transcludeScope.$destroy)); }; })(childTranscludeFn || transcludeFn) ); @@ -4032,7 +4624,7 @@ function $CompileProvider($provide) { * @param attrs The shared attrs object which is used to populate the normalized attributes. * @param {number=} maxPriority Max directive priority. */ - function collectDirectives(node, directives, attrs, maxPriority) { + function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) { var nodeType = node.nodeType, attrsMap = attrs.$attr, match, @@ -4042,14 +4634,28 @@ function $CompileProvider($provide) { case 1: /* Element */ // use the node name: addDirective(directives, - directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority); + directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective); // iterate over the attributes - for (var attr, name, nName, value, nAttrs = node.attributes, + for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes, j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { + var attrStartName; + var attrEndName; + var index; + attr = nAttrs[j]; - if (attr.specified) { + if (!msie || msie >= 8 || attr.specified) { name = attr.name; + // support ngAttr attribute binding + ngAttrName = directiveNormalize(name); + if (NG_ATTR_BINDING.test(ngAttrName)) { + name = ngAttrName.substr(6).toLowerCase(); + } + if ((index = ngAttrName.lastIndexOf('Start')) != -1 && index == ngAttrName.length - 5) { + attrStartName = name; + attrEndName = name.substr(0, name.length - 5) + 'end'; + name = name.substr(0, name.length - 6); + } nName = directiveNormalize(name.toLowerCase()); attrsMap[nName] = name; attrs[nName] = value = trim((msie && name == 'href') @@ -4059,7 +4665,7 @@ function $CompileProvider($provide) { attrs[nName] = true; // presence means true } addAttrInterpolateDirective(node, directives, value, nName); - addDirective(directives, nName, 'A', maxPriority); + addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, attrEndName); } } @@ -4068,7 +4674,7 @@ function $CompileProvider($provide) { if (isString(className) && className !== '') { while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { nName = directiveNormalize(match[2]); - if (addDirective(directives, nName, 'C', maxPriority)) { + if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) { attrs[nName] = trim(match[3]); } className = className.substr(match.index + match[0].length); @@ -4083,7 +4689,7 @@ function $CompileProvider($provide) { match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); if (match) { nName = directiveNormalize(match[1]); - if (addDirective(directives, nName, 'M', maxPriority)) { + if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { attrs[nName] = trim(match[2]); } } @@ -4098,6 +4704,49 @@ function $CompileProvider($provide) { return directives; } + /** + * Given a node with an directive-start it collects all of the siblings until it find directive-end. + * @param node + * @param attrStart + * @param attrEnd + * @returns {*} + */ + function groupScan(node, attrStart, attrEnd) { + var nodes = []; + var depth = 0; + if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { + var startNode = node; + do { + if (!node) { + throw $compileMinErr('uterdir', "Unterminated attribute, found '{0}' but no matching '{1}' found.", attrStart, attrEnd); + } + if (node.nodeType == 1 /** Element **/) { + if (node.hasAttribute(attrStart)) depth++; + if (node.hasAttribute(attrEnd)) depth--; + } + nodes.push(node); + node = node.nextSibling; + } while (depth > 0); + } else { + nodes.push(node); + } + return jqLite(nodes); + } + + /** + * Wrapper for linking function which converts normal linking function into a grouped + * linking function. + * @param linkFn + * @param attrStart + * @param attrEnd + * @returns {Function} + */ + function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) { + return function(scope, element, attrs, controllers) { + element = groupScan(element[0], attrStart, attrEnd); + return linkFn(scope, element, attrs, controllers); + } + } /** * Once the directives have been collected, their compile functions are executed. This method @@ -4114,7 +4763,7 @@ function $CompileProvider($provide) { * argument has the root jqLite array so that we can replace nodes on it. * @returns linkFn */ - function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection) { + function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection, originalReplaceDirective) { var terminalPriority = -Number.MAX_VALUE, preLinkFns = [], postLinkFns = [], @@ -4126,6 +4775,7 @@ function $CompileProvider($provide) { directiveName, $template, transcludeDirective, + replaceDirective = originalReplaceDirective, childTranscludeFn = transcludeFn, controllerDirectives, linkFn, @@ -4134,7 +4784,14 @@ function $CompileProvider($provide) { // executes all directives on the current element for(var i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; - $template = undefined; + var attrStart = directive.$$start; + var attrEnd = directive.$$end; + + // collect multiblock sections + if (attrStart) { + $compileNode = groupScan(compileNode, attrStart, attrEnd) + } + $template = undefined; if (terminalPriority > directive.priority) { break; // prevent further processing of directives @@ -4164,12 +4821,14 @@ function $CompileProvider($provide) { transcludeDirective = directive; terminalPriority = directive.priority; if (directiveValue == 'element') { - $template = jqLite(compileNode); + $template = groupScan(compileNode, attrStart, attrEnd) $compileNode = templateAttrs.$$element = jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' ')); compileNode = $compileNode[0]; - replaceWith(jqCollection, jqLite($template[0]), compileNode); - childTranscludeFn = compile($template, transcludeFn, terminalPriority); + replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode); + + childTranscludeFn = compile($template, transcludeFn, terminalPriority, + replaceDirective && replaceDirective.name); } else { $template = jqLite(JQLiteClone(compileNode)).contents(); $compileNode.html(''); // clear contents @@ -4177,19 +4836,25 @@ function $CompileProvider($provide) { } } - if ((directiveValue = directive.template)) { + if (directive.template) { assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; + + directiveValue = (isFunction(directive.template)) + ? directive.template($compileNode, templateAttrs) + : directive.template; + directiveValue = denormalizeTemplate(directiveValue); if (directive.replace) { + replaceDirective = directive; $template = jqLite('
' + trim(directiveValue) + '
').contents(); compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { - throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue); + throw $compileMinErr('tplrt', "Template for directive '{0}' must have exactly one root element. {1}", directiveName, ''); } replaceWith(jqCollection, $compileNode, compileNode); @@ -4219,17 +4884,20 @@ function $CompileProvider($provide) { if (directive.templateUrl) { assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; + + if (directive.replace) { + replaceDirective = directive; + } nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), - nodeLinkFn, $compileNode, templateAttrs, jqCollection, directive.replace, - childTranscludeFn); + nodeLinkFn, $compileNode, templateAttrs, jqCollection, childTranscludeFn); ii = directives.length; } else if (directive.compile) { try { linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); if (isFunction(linkFn)) { - addLinkFns(null, linkFn); + addLinkFns(null, linkFn, attrStart, attrEnd); } else if (linkFn) { - addLinkFns(linkFn.pre, linkFn.post); + addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd); } } catch (e) { $exceptionHandler(e, startingTag($compileNode)); @@ -4251,12 +4919,14 @@ function $CompileProvider($provide) { //////////////////// - function addLinkFns(pre, post) { + function addLinkFns(pre, post, attrStart, attrEnd) { if (pre) { + if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd); pre.require = directive.require; preLinkFns.push(pre); } if (post) { + if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); post.require = directive.require; postLinkFns.push(post); } @@ -4275,7 +4945,7 @@ function $CompileProvider($provide) { } value = $element[retrievalMethod]('$' + require + 'Controller'); if (!value && !optional) { - throw Error("No controller: " + require); + throw $compileMinErr('ctreq', "Controller '{0}', required by directive '{1}', can't be found!", require, directiveName); } return value; } else if (isArray(require)) { @@ -4299,13 +4969,14 @@ function $CompileProvider($provide) { $element = attrs.$$element; if (newIsolateScopeDirective) { - var LOCAL_REGEXP = /^\s*([@=&])\s*(\w*)\s*$/; + var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/; var parentScope = scope.$parent || scope; - forEach(newIsolateScopeDirective.scope, function(definiton, scopeName) { - var match = definiton.match(LOCAL_REGEXP) || [], - attrName = match[2]|| scopeName, + forEach(newIsolateScopeDirective.scope, function(definition, scopeName) { + var match = definition.match(LOCAL_REGEXP) || [], + attrName = match[3] || scopeName, + optional = (match[2] == '?'), mode = match[1], // @, =, or & lastValue, parentGet, parentSet; @@ -4319,16 +4990,23 @@ function $CompileProvider($provide) { scope[scopeName] = value; }); attrs.$$observers[attrName].$$scope = parentScope; + if( attrs[attrName] ) { + // If the attribute has been provided then we trigger an interpolation to ensure the value is there for use in the link fn + scope[scopeName] = $interpolate(attrs[attrName])(parentScope); + } break; } case '=': { + if (optional && !attrs[attrName]) { + return; + } parentGet = $parse(attrs[attrName]); parentSet = parentGet.assign || function() { // reset the change, or we will throw this exception on every $digest lastValue = scope[scopeName] = parentGet(parentScope); - throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] + - ' (directive: ' + newIsolateScopeDirective.name + ')'); + throw $compileMinErr('nonassign', "Expression '{0}' used with directive '{1}' is non-assignable!", + attrs[attrName], newIsolateScopeDirective.name); }; lastValue = scope[scopeName] = parentGet(parentScope); scope.$watch(function parentValueWatch() { @@ -4358,8 +5036,8 @@ function $CompileProvider($provide) { } default: { - throw Error('Invalid isolate scope definition for directive ' + - newIsolateScopeDirective.name + ': ' + definiton); + throw $compileMinErr('iscp', "Invalid isolate scope definition for directive '{0}'. Definition: {... {1}: '{2}' ...}", + newIsolateScopeDirective.name, scopeName, definition); } } }); @@ -4372,16 +5050,20 @@ function $CompileProvider($provide) { $element: $element, $attrs: attrs, $transclude: boundTranscludeFn - }; + }, controllerInstance; controller = directive.controller; if (controller == '@') { controller = attrs[directive.name]; } + controllerInstance = $controller(controller, locals); $element.data( '$' + directive.name + 'Controller', - $controller(controller, locals)); + controllerInstance); + if (directive.controllerAs) { + locals.$scope[directive.controllerAs] = controllerInstance; + } }); } @@ -4427,8 +5109,9 @@ function $CompileProvider($provide) { * * `M`: comment * @returns true if directive was added. */ - function addDirective(tDirectives, name, location, maxPriority) { - var match = false; + function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName, endAttrName) { + if (name === ignoreDirective) return null; + var match = null; if (hasDirectives.hasOwnProperty(name)) { for(var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i directive.priority) && directive.restrict.indexOf(location) != -1) { + if (startAttrName) { + directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); + } tDirectives.push(directive); - match = true; + match = directive; } } catch(e) { $exceptionHandler(e); } } @@ -4485,7 +5171,7 @@ function $CompileProvider($provide) { function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs, - $rootElement, replace, childTranscludeFn) { + $rootElement, childTranscludeFn) { var linkQueue = [], afterTemplateNodeLinkFn, afterTemplateChildLinkFn, @@ -4493,23 +5179,27 @@ function $CompileProvider($provide) { origAsyncDirective = directives.shift(), // The fact that we have to copy and patch the directive seems wrong! derivedSyncDirective = extend({}, origAsyncDirective, { - controller: null, templateUrl: null, transclude: null, scope: null - }); + controller: null, templateUrl: null, transclude: null, scope: null, replace: null + }), + templateUrl = (isFunction(origAsyncDirective.templateUrl)) + ? origAsyncDirective.templateUrl($compileNode, tAttrs) + : origAsyncDirective.templateUrl; $compileNode.html(''); - $http.get(origAsyncDirective.templateUrl, {cache: $templateCache}). + $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}). success(function(content) { var compileNode, tempTemplateAttrs, $template; content = denormalizeTemplate(content); - if (replace) { + if (origAsyncDirective.replace) { $template = jqLite('
' + trim(content) + '
').contents(); compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { - throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content); + throw $compileMinErr('tplrt', "Template for directive '{0}' must have exactly one root element. {1}", + origAsyncDirective.name, templateUrl); } tempTemplateAttrs = {$attr: {}}; @@ -4522,16 +5212,22 @@ function $CompileProvider($provide) { } directives.unshift(derivedSyncDirective); - afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn); + + afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn, $compileNode, origAsyncDirective); + forEach($rootElement, function(node, i) { + if (node == compileNode) { + $rootElement[i] = $compileNode[0]; + } + }); afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); while(linkQueue.length) { - var controller = linkQueue.pop(), - linkRootElement = linkQueue.pop(), - beforeTemplateLinkNode = linkQueue.pop(), - scope = linkQueue.pop(), - linkNode = compileNode; + var scope = linkQueue.shift(), + beforeTemplateLinkNode = linkQueue.shift(), + linkRootElement = linkQueue.shift(), + controller = linkQueue.shift(), + linkNode = $compileNode[0]; if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { // it was cloned therefore we have to clone as well. @@ -4539,14 +5235,15 @@ function $CompileProvider($provide) { replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); } - afterTemplateNodeLinkFn(function() { - beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller); - }, scope, linkNode, $rootElement, controller); + afterTemplateNodeLinkFn( + beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller), + scope, linkNode, $rootElement, controller + ); } linkQueue = null; }). error(function(response, code, headers, config) { - throw Error('Failed to load template: ' + config.url); + throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url); }); return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) { @@ -4574,8 +5271,8 @@ function $CompileProvider($provide) { function assertNoDuplicate(what, previousDirective, directive, element) { if (previousDirective) { - throw Error('Multiple directives [' + previousDirective.name + ', ' + - directive.name + '] asking for ' + what + ' on: ' + startingTag(element)); + throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}', + previousDirective.name, directive.name, what, startingTag(element)); } } @@ -4599,6 +5296,16 @@ function $CompileProvider($provide) { } + function getTrustedContext(node, attrNormalizedName) { + // maction[xlink:href] can source SVG. It's not limited to . + if (attrNormalizedName == "xlinkHref" || + (nodeName_(node) != "IMG" && (attrNormalizedName == "src" || + attrNormalizedName == "ngSrc"))) { + return $sce.RESOURCE_URL; + } + } + + function addAttrInterpolateDirective(node, directives, value, name) { var interpolateFn = $interpolate(value, true); @@ -4606,18 +5313,31 @@ function $CompileProvider($provide) { if (!interpolateFn) return; + if (name === "multiple" && nodeName_(node) === "SELECT") { + throw $compileMinErr("selmulti", "Binding to the 'multiple' attribute is not supported. Element: {0}", + startingTag(node)); + } + directives.push({ priority: 100, compile: valueFn(function attrInterpolateLinkFn(scope, element, attr) { var $$observers = (attr.$$observers || (attr.$$observers = {})); - if (name === 'class') { - // we need to interpolate classes again, in the case the element was replaced - // and therefore the two class attrs got merged - we want to interpolate the result - interpolateFn = $interpolate(attr[name], true); + if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { + throw $compileMinErr('nodomevents', + "Interpolations for HTML DOM event attributes are disallowed. Please use the ng- " + + "versions (such as ng-click instead of onclick) instead."); } - attr[name] = undefined; + // we need to interpolate again, in case the attribute value has been updated + // (e.g. by another directive's compile function) + interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name)); + + // if attribute was updated so that there is no interpolation going on we don't want to + // register any observers + if (!interpolateFn) return; + + attr[name] = interpolateFn(scope); ($$observers[name] || ($$observers[name] = [])).$$inter = true; (attr.$$observers && attr.$$observers[name].$$scope || scope). $watch(interpolateFn, function interpolateFnWatchAction(value) { @@ -4634,30 +5354,50 @@ function $CompileProvider($provide) { * * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes * in the root of the tree. - * @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell, + * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep the shell, * but replace its DOM node reference. * @param {Node} newNode The new DOM node. */ - function replaceWith($rootElement, $element, newNode) { - var oldNode = $element[0], - parent = oldNode.parentNode, + function replaceWith($rootElement, elementsToRemove, newNode) { + var firstElementToRemove = elementsToRemove[0], + removeCount = elementsToRemove.length, + parent = firstElementToRemove.parentNode, i, ii; if ($rootElement) { for(i = 0, ii = $rootElement.length; i < ii; i++) { - if ($rootElement[i] == oldNode) { - $rootElement[i] = newNode; + if ($rootElement[i] == firstElementToRemove) { + $rootElement[i++] = newNode; + for (var j = i, j2 = j + removeCount - 1, + jj = $rootElement.length; + j < jj; j++, j2++) { + if (j2 < jj) { + $rootElement[j] = $rootElement[j2]; + } else { + delete $rootElement[j]; + } + } + $rootElement.length -= removeCount - 1; break; } } } if (parent) { - parent.replaceChild(newNode, oldNode); + parent.replaceChild(newNode, firstElementToRemove); + } + var fragment = document.createDocumentFragment(); + fragment.appendChild(firstElementToRemove); + newNode[jqLite.expando] = firstElementToRemove[jqLite.expando]; + for (var k = 1, kk = elementsToRemove.length; k < kk; k++) { + var element = elementsToRemove[k]; + jqLite(element).remove(); // must do this way to clean up expando + fragment.appendChild(element); + delete elementsToRemove[k]; } - newNode[jqLite.expando] = oldNode[jqLite.expando]; - $element[0] = newNode; + elementsToRemove[0] = newNode; + elementsToRemove.length = 1 } }]; } @@ -4666,7 +5406,7 @@ var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; /** * Converts all accepted directives format into proper directive name. * All of these will become 'myDirective': - * my:DiRective + * my:Directive * my-directive * x-my-directive * data-my:directive @@ -4712,7 +5452,7 @@ function directiveNormalize(name) { * @param {string} name Normalized element attribute name of the property to modify. The name is * revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr} * property to the original name. - * @param {string} value Value to set the attribute to. + * @param {string} value Value to set the attribute to. The value can be an interpolated string. */ @@ -4747,7 +5487,8 @@ function directiveLinkingFn( * {@link ng.$controllerProvider#register register} method. */ function $ControllerProvider() { - var controllers = {}; + var controllers = {}, + CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; /** @@ -4792,17 +5533,31 @@ function $ControllerProvider() { * a service, so that one can override this service with {@link https://gist.github.com/1649788 * BC version}. */ - return function(constructor, locals) { - if(isString(constructor)) { - var name = constructor; - constructor = controllers.hasOwnProperty(name) - ? controllers[name] - : getter(locals.$scope, name, true) || getter($window, name, true); + return function(expression, locals) { + var instance, match, constructor, identifier; + + if(isString(expression)) { + match = expression.match(CNTRL_REG), + constructor = match[1], + identifier = match[3]; + expression = controllers.hasOwnProperty(constructor) + ? controllers[constructor] + : getter(locals.$scope, constructor, true) || getter($window, constructor, true); + + assertArgFn(expression, constructor, true); + } - assertArgFn(constructor, name, true); + instance = $injector.instantiate(expression, locals); + + if (identifier) { + if (!(locals && typeof locals.$scope == 'object')) { + throw minErr('$controller')('noscp', "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.", constructor || expression.name, identifier); + } + + locals.$scope[identifier] = instance; } - return $injector.instantiate(constructor, locals); + return instance; }; }]; } @@ -4849,4586 +5604,5674 @@ function $ExceptionHandlerProvider() { } /** - * @ngdoc object - * @name ng.$interpolateProvider - * @function - * - * @description + * Parse headers into key value object * - * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. + * @param {string} headers Raw headers as a string + * @returns {Object} Parsed headers as key value object */ -function $InterpolateProvider() { - var startSymbol = '{{'; - var endSymbol = '}}'; - - /** - * @ngdoc method - * @name ng.$interpolateProvider#startSymbol - * @methodOf ng.$interpolateProvider - * @description - * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. - * - * @param {string=} value new value to set the starting symbol to. - * @returns {string|self} Returns the symbol when used as getter and self if used as setter. - */ - this.startSymbol = function(value){ - if (value) { - startSymbol = value; - return this; - } else { - return startSymbol; - } - }; - - /** - * @ngdoc method - * @name ng.$interpolateProvider#endSymbol - * @methodOf ng.$interpolateProvider - * @description - * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. - * - * @param {string=} value new value to set the ending symbol to. - * @returns {string|self} Returns the symbol when used as getter and self if used as setter. - */ - this.endSymbol = function(value){ - if (value) { - endSymbol = value; - return this; - } else { - return endSymbol; - } - }; - - - this.$get = ['$parse', function($parse) { - var startSymbolLength = startSymbol.length, - endSymbolLength = endSymbol.length; - - /** - * @ngdoc function - * @name ng.$interpolate - * @function - * - * @requires $parse - * - * @description - * - * Compiles a string with markup into an interpolation function. This service is used by the - * HTML {@link ng.$compile $compile} service for data binding. See - * {@link ng.$interpolateProvider $interpolateProvider} for configuring the - * interpolation markup. - * - * -
-         var $interpolate = ...; // injected
-         var exp = $interpolate('Hello {{name}}!');
-         expect(exp({name:'Angular'}).toEqual('Hello Angular!');
-       
- * - * - * @param {string} text The text with markup to interpolate. - * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have - * embedded expression in order to return an interpolation function. Strings with no - * embedded expression will return null for the interpolation function. - * @returns {function(context)} an interpolation function which is used to compute the interpolated - * string. The function has these parameters: - * - * * `context`: an object against which any expressions embedded in the strings are evaluated - * against. - * - */ - function $interpolate(text, mustHaveExpression) { - var startIndex, - endIndex, - index = 0, - parts = [], - length = text.length, - hasInterpolation = false, - fn, - exp, - concat = []; +function parseHeaders(headers) { + var parsed = {}, key, val, i; - while(index < length) { - if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && - ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { - (index != startIndex) && parts.push(text.substring(index, startIndex)); - parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex))); - fn.exp = exp; - index = endIndex + endSymbolLength; - hasInterpolation = true; - } else { - // we did not find anything, so we have to add the remainder to the parts array - (index != length) && parts.push(text.substring(index)); - index = length; - } - } + if (!headers) return parsed; - if (!(length = parts.length)) { - // we added, nothing, must have been an empty string. - parts.push(''); - length = 1; - } + forEach(headers.split('\n'), function(line) { + i = line.indexOf(':'); + key = lowercase(trim(line.substr(0, i))); + val = trim(line.substr(i + 1)); - if (!mustHaveExpression || hasInterpolation) { - concat.length = length; - fn = function(context) { - for(var i = 0, ii = length, part; i)} fns Function or an array of functions. + * @returns {*} Transformed data. */ -function encodePath(path) { - var segments = path.split('/'), - i = segments.length; +function transformData(data, headers, fns) { + if (isFunction(fns)) + return fns(data, headers); - while (i--) { - segments[i] = encodeUriSegment(segments[i]); - } + forEach(fns, function(fn) { + data = fn(data, headers); + }); - return segments.join('/'); + return data; } -function stripHash(url) { - return url.split('#')[0]; -} - -function matchUrl(url, obj) { - var match = URL_MATCH.exec(url); - - match = { - protocol: match[1], - host: match[3], - port: int(match[5]) || DEFAULT_PORTS[match[1]] || null, - path: match[6] || '/', - search: match[8], - hash: match[10] - }; - - if (obj) { - obj.$$protocol = match.protocol; - obj.$$host = match.host; - obj.$$port = match.port; - } - - return match; -} - - -function composeProtocolHostPort(protocol, host, port) { - return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port); -} - - -function pathPrefixFromBase(basePath) { - return basePath.substr(0, basePath.lastIndexOf('/')); -} - - -function convertToHtml5Url(url, basePath, hashPrefix) { - var match = matchUrl(url); - - // already html5 url - if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) || - match.hash.indexOf(hashPrefix) !== 0) { - return url; - // convert hashbang url -> html5 url - } else { - return composeProtocolHostPort(match.protocol, match.host, match.port) + - pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length); - } -} - - -function convertToHashbangUrl(url, basePath, hashPrefix) { - var match = matchUrl(url); - - // already hashbang url - if (decodeURIComponent(match.path) == basePath && !isUndefined(match.hash) && - match.hash.indexOf(hashPrefix) === 0) { - return url; - // convert html5 url -> hashbang url - } else { - var search = match.search && '?' + match.search || '', - hash = match.hash && '#' + match.hash || '', - pathPrefix = pathPrefixFromBase(basePath), - path = match.path.substr(pathPrefix.length); - - if (match.path.indexOf(pathPrefix) !== 0) { - throw Error('Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !'); - } - - return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath + - '#' + hashPrefix + path + search + hash; - } -} - - -/** - * LocationUrl represents an url - * This object is exposed as $location service when HTML5 mode is enabled and supported - * - * @constructor - * @param {string} url HTML5 url - * @param {string} pathPrefix - */ -function LocationUrl(url, pathPrefix, appBaseUrl) { - pathPrefix = pathPrefix || ''; - - /** - * Parse given html5 (regular) url string into properties - * @param {string} newAbsoluteUrl HTML5 url - * @private - */ - this.$$parse = function(newAbsoluteUrl) { - var match = matchUrl(newAbsoluteUrl, this); - - if (match.path.indexOf(pathPrefix) !== 0) { - throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefix "' + pathPrefix + '" !'); - } - - this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length)); - this.$$search = parseKeyValue(match.search); - this.$$hash = match.hash && decodeURIComponent(match.hash) || ''; - - this.$$compose(); - }; - - /** - * Compose url and update `absUrl` property - * @private - */ - this.$$compose = function() { - var search = toKeyValue(this.$$search), - hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; - - this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; - this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + - pathPrefix + this.$$url; - }; - - - this.$$rewriteAppUrl = function(absoluteLinkUrl) { - if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) { - return absoluteLinkUrl; - } - } - - - this.$$parse(url); +function isSuccess(status) { + return 200 <= status && status < 300; } -/** - * LocationHashbangUrl represents url - * This object is exposed as $location service when html5 history api is disabled or not supported - * - * @constructor - * @param {string} url Legacy url - * @param {string} hashPrefix Prefix for hash part (containing path and search) - */ -function LocationHashbangUrl(url, hashPrefix, appBaseUrl) { - var basePath; - - /** - * Parse given hashbang url into properties - * @param {string} url Hashbang url - * @private - */ - this.$$parse = function(url) { - var match = matchUrl(url, this); - - - if (match.hash && match.hash.indexOf(hashPrefix) !== 0) { - throw Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !'); - } - - basePath = match.path + (match.search ? '?' + match.search : ''); - match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length)); - if (match[1]) { - this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]); - } else { - this.$$path = ''; - } +function $HttpProvider() { + var JSON_START = /^\s*(\[|\{[^\{])/, + JSON_END = /[\}\]]\s*$/, + PROTECTION_PREFIX = /^\)\]\}',?\n/, + CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'}; - this.$$search = parseKeyValue(match[3]); - this.$$hash = match[5] && decodeURIComponent(match[5]) || ''; + var defaults = this.defaults = { + // transform incoming response data + transformResponse: [function(data) { + if (isString(data)) { + // strip json vulnerability protection prefix + data = data.replace(PROTECTION_PREFIX, ''); + if (JSON_START.test(data) && JSON_END.test(data)) + data = fromJson(data, true); + } + return data; + }], - this.$$compose(); - }; + // transform outgoing request data + transformRequest: [function(d) { + return isObject(d) && !isFile(d) ? toJson(d) : d; + }], - /** - * Compose hashbang url and update `absUrl` property - * @private - */ - this.$$compose = function() { - var search = toKeyValue(this.$$search), - hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; + // default headers + headers: { + common: { + 'Accept': 'application/json, text/plain, */*' + }, + post: CONTENT_TYPE_APPLICATION_JSON, + put: CONTENT_TYPE_APPLICATION_JSON, + patch: CONTENT_TYPE_APPLICATION_JSON + }, - this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; - this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + - basePath + (this.$$url ? '#' + hashPrefix + this.$$url : ''); + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN' }; - this.$$rewriteAppUrl = function(absoluteLinkUrl) { - if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) { - return absoluteLinkUrl; - } - } - - - this.$$parse(url); -} - - -LocationUrl.prototype = { - - /** - * Has any change been replacing ? - * @private - */ - $$replace: false, - /** - * @ngdoc method - * @name ng.$location#absUrl - * @methodOf ng.$location - * - * @description - * This method is getter only. - * - * Return full url representation with all segments encoded according to rules specified in - * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}. - * - * @return {string} full url + * Are order by request. I.E. they are applied in the same order as + * array on request, but revers order on response. */ - absUrl: locationGetter('$$absUrl'), - + var interceptorFactories = this.interceptors = []; /** - * @ngdoc method - * @name ng.$location#url - * @methodOf ng.$location - * - * @description - * This method is getter / setter. - * - * Return url (e.g. `/path?a=b#hash`) when called without any parameter. - * - * Change path, search and hash, when called with parameter and return `$location`. - * - * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) - * @return {string} url + * For historical reasons, response interceptors ordered by the order in which + * they are applied to response. (This is in revers to interceptorFactories) */ - url: function(url, replace) { - if (isUndefined(url)) - return this.$$url; + var responseInterceptorFactories = this.responseInterceptors = []; - var match = PATH_MATCH.exec(url); - if (match[1]) this.path(decodeURIComponent(match[1])); - if (match[2] || match[1]) this.search(match[3] || ''); - this.hash(match[5] || '', replace); + this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', '$$urlUtils', + function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector, $$urlUtils) { - return this; - }, + var defaultCache = $cacheFactory('$http'); - /** - * @ngdoc method - * @name ng.$location#protocol - * @methodOf ng.$location - * - * @description - * This method is getter only. - * - * Return protocol of current url. - * - * @return {string} protocol of current url - */ - protocol: locationGetter('$$protocol'), + /** + * Interceptors stored in reverse order. Inner interceptors before outer interceptors. + * The reversal is needed so that we can build up the interception chain around the + * server request. + */ + var reversedInterceptors = []; - /** - * @ngdoc method - * @name ng.$location#host - * @methodOf ng.$location - * - * @description - * This method is getter only. - * - * Return host of current url. - * - * @return {string} host of current url. - */ - host: locationGetter('$$host'), + forEach(interceptorFactories, function(interceptorFactory) { + reversedInterceptors.unshift(isString(interceptorFactory) + ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); + }); - /** - * @ngdoc method - * @name ng.$location#port - * @methodOf ng.$location - * - * @description - * This method is getter only. - * - * Return port of current url. - * - * @return {Number} port - */ - port: locationGetter('$$port'), + forEach(responseInterceptorFactories, function(interceptorFactory, index) { + var responseFn = isString(interceptorFactory) + ? $injector.get(interceptorFactory) + : $injector.invoke(interceptorFactory); - /** - * @ngdoc method - * @name ng.$location#path - * @methodOf ng.$location - * - * @description - * This method is getter / setter. - * - * Return path of current url when called without any parameter. - * - * Change path when called with parameter and return `$location`. - * - * Note: Path should always begin with forward slash (/), this method will add the forward slash - * if it is missing. - * - * @param {string=} path New path - * @return {string} path - */ - path: locationGetterSetter('$$path', function(path) { - return path.charAt(0) == '/' ? path : '/' + path; - }), + /** + * Response interceptors go before "around" interceptors (no real reason, just + * had to pick one.) But they are already reversed, so we can't use unshift, hence + * the splice. + */ + reversedInterceptors.splice(index, 0, { + response: function(response) { + return responseFn($q.when(response)); + }, + responseError: function(response) { + return responseFn($q.reject(response)); + } + }); + }); - /** - * @ngdoc method - * @name ng.$location#search - * @methodOf ng.$location - * - * @description - * This method is getter / setter. - * - * Return search part (as object) of current url when called without any parameter. - * - * Change search part when called with parameter and return `$location`. - * - * @param {string|object=} search New search params - string or hash object - * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a - * single search parameter. If the value is `null`, the parameter will be deleted. - * - * @return {string} search - */ - search: function(search, paramValue) { - if (isUndefined(search)) - return this.$$search; - if (isDefined(paramValue)) { - if (paramValue === null) { - delete this.$$search[search]; - } else { - this.$$search[search] = paramValue; - } - } else { - this.$$search = isString(search) ? parseKeyValue(search) : search; - } - - this.$$compose(); - return this; - }, - - /** - * @ngdoc method - * @name ng.$location#hash - * @methodOf ng.$location - * - * @description - * This method is getter / setter. - * - * Return hash fragment when called without any parameter. - * - * Change hash fragment when called with parameter and return `$location`. - * - * @param {string=} hash New hash fragment - * @return {string} hash - */ - hash: locationGetterSetter('$$hash', identity), - - /** - * @ngdoc method - * @name ng.$location#replace - * @methodOf ng.$location - * - * @description - * If called, all changes to $location during current `$digest` will be replacing current history - * record, instead of adding new one. - */ - replace: function() { - this.$$replace = true; - return this; - } -}; - -LocationHashbangUrl.prototype = inherit(LocationUrl.prototype); - -function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) { - LocationHashbangUrl.apply(this, arguments); - - - this.$$rewriteAppUrl = function(absoluteLinkUrl) { - if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) { - return appBaseUrl + baseExtra + '#' + hashPrefix + absoluteLinkUrl.substr(appBaseUrl.length); - } - } -} - -LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype); - -function locationGetter(property) { - return function() { - return this[property]; - }; -} - - -function locationGetterSetter(property, preprocess) { - return function(value) { - if (isUndefined(value)) - return this[property]; - - this[property] = preprocess(value); - this.$$compose(); - - return this; - }; -} - - -/** - * @ngdoc object - * @name ng.$location - * - * @requires $browser - * @requires $sniffer - * @requires $rootElement - * - * @description - * The $location service parses the URL in the browser address bar (based on the - * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL - * available to your application. Changes to the URL in the address bar are reflected into - * $location service and changes to $location are reflected into the browser address bar. - * - * **The $location service:** - * - * - Exposes the current URL in the browser address bar, so you can - * - Watch and observe the URL. - * - Change the URL. - * - Synchronizes the URL with the browser when the user - * - Changes the address bar. - * - Clicks the back or forward button (or clicks a History link). - * - Clicks on a link. - * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). - * - * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular - * Services: Using $location} - */ - -/** - * @ngdoc object - * @name ng.$locationProvider - * @description - * Use the `$locationProvider` to configure how the application deep linking paths are stored. - */ -function $LocationProvider(){ - var hashPrefix = '', - html5Mode = false; - - /** - * @ngdoc property - * @name ng.$locationProvider#hashPrefix - * @methodOf ng.$locationProvider - * @description - * @param {string=} prefix Prefix for hash part (containing path and search) - * @returns {*} current value if used as getter or itself (chaining) if used as setter - */ - this.hashPrefix = function(prefix) { - if (isDefined(prefix)) { - hashPrefix = prefix; - return this; - } else { - return hashPrefix; - } - }; - - /** - * @ngdoc property - * @name ng.$locationProvider#html5Mode - * @methodOf ng.$locationProvider - * @description - * @param {string=} mode Use HTML5 strategy if available. - * @returns {*} current value if used as getter or itself (chaining) if used as setter - */ - this.html5Mode = function(mode) { - if (isDefined(mode)) { - html5Mode = mode; - return this; - } else { - return html5Mode; - } - }; - - this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', - function( $rootScope, $browser, $sniffer, $rootElement) { - var $location, - basePath, - pathPrefix, - initUrl = $browser.url(), - initUrlParts = matchUrl(initUrl), - appBaseUrl; - - if (html5Mode) { - basePath = $browser.baseHref() || '/'; - pathPrefix = pathPrefixFromBase(basePath); - appBaseUrl = - composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) + - pathPrefix + '/'; - - if ($sniffer.history) { - $location = new LocationUrl( - convertToHtml5Url(initUrl, basePath, hashPrefix), - pathPrefix, appBaseUrl); - } else { - $location = new LocationHashbangInHtml5Url( - convertToHashbangUrl(initUrl, basePath, hashPrefix), - hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1)); - } - } else { - appBaseUrl = - composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) + - (initUrlParts.path || '') + - (initUrlParts.search ? ('?' + initUrlParts.search) : '') + - '#' + hashPrefix + '/'; - - $location = new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl); - } - - $rootElement.bind('click', function(event) { - // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) - // currently we open nice url link and redirect then - - if (event.ctrlKey || event.metaKey || event.which == 2) return; - - var elm = jqLite(event.target); - - // traverse the DOM up to find first A tag - while (lowercase(elm[0].nodeName) !== 'a') { - // ignore rewriting if no A tag (reached root element, or no parent - removed from document) - if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; - } - - var absHref = elm.prop('href'), - rewrittenUrl = $location.$$rewriteAppUrl(absHref); - - if (absHref && !elm.attr('target') && rewrittenUrl) { - // update location manually - $location.$$parse(rewrittenUrl); - $rootScope.$apply(); - event.preventDefault(); - // hack to work around FF6 bug 684208 when scenario runner clicks on links - window.angular['ff-684208-preventDefault'] = true; - } - }); - - - // rewrite hashbang url <> html5 url - if ($location.absUrl() != initUrl) { - $browser.url($location.absUrl(), true); - } - - // update $location when $browser url changes - $browser.onUrlChange(function(newUrl) { - if ($location.absUrl() != newUrl) { - if ($rootScope.$broadcast('$locationChangeStart', newUrl, $location.absUrl()).defaultPrevented) { - $browser.url($location.absUrl()); - return; - } - $rootScope.$evalAsync(function() { - var oldUrl = $location.absUrl(); - - $location.$$parse(newUrl); - afterLocationChange(oldUrl); - }); - if (!$rootScope.$$phase) $rootScope.$digest(); - } - }); - - // update browser - var changeCounter = 0; - $rootScope.$watch(function $locationWatch() { - var oldUrl = $browser.url(); - var currentReplace = $location.$$replace; - - if (!changeCounter || oldUrl != $location.absUrl()) { - changeCounter++; - $rootScope.$evalAsync(function() { - if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl). - defaultPrevented) { - $location.$$parse(oldUrl); - } else { - $browser.url($location.absUrl(), currentReplace); - afterLocationChange(oldUrl); - } - }); - } - $location.$$replace = false; - - return changeCounter; - }); - - return $location; - - function afterLocationChange(oldUrl) { - $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl); - } -}]; -} - -/** - * @ngdoc object - * @name ng.$log - * @requires $window - * - * @description - * Simple service for logging. Default implementation writes the message - * into the browser's console (if present). - * - * The main purpose of this service is to simplify debugging and troubleshooting. - * - * @example - - - function LogCtrl($scope, $log) { - $scope.$log = $log; - $scope.message = 'Hello World!'; - } - - -
-

Reload this page with open console, enter text and hit the log button...

- Message: - - - - - -
-
-
- */ - -function $LogProvider(){ - this.$get = ['$window', function($window){ - return { - /** - * @ngdoc method - * @name ng.$log#log - * @methodOf ng.$log - * - * @description - * Write a log message - */ - log: consoleLog('log'), - - /** - * @ngdoc method - * @name ng.$log#warn - * @methodOf ng.$log - * - * @description - * Write a warning message - */ - warn: consoleLog('warn'), - - /** - * @ngdoc method - * @name ng.$log#info - * @methodOf ng.$log - * - * @description - * Write an information message - */ - info: consoleLog('info'), - - /** - * @ngdoc method - * @name ng.$log#error - * @methodOf ng.$log - * - * @description - * Write an error message - */ - error: consoleLog('error') - }; - - function formatError(arg) { - if (arg instanceof Error) { - if (arg.stack) { - arg = (arg.message && arg.stack.indexOf(arg.message) === -1) - ? 'Error: ' + arg.message + '\n' + arg.stack - : arg.stack; - } else if (arg.sourceURL) { - arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; - } - } - return arg; - } - - function consoleLog(type) { - var console = $window.console || {}, - logFn = console[type] || console.log || noop; - - if (logFn.apply) { - return function() { - var args = []; - forEach(arguments, function(arg) { - args.push(formatError(arg)); - }); - return logFn.apply(console, args); - }; - } - - // we are IE which either doesn't have window.console => this is noop and we do nothing, - // or we are IE where console.log doesn't have apply so we log at least first 2 args - return function(arg1, arg2) { - logFn(arg1, arg2); - } - } - }]; -} - -var OPERATORS = { - 'null':function(){return null;}, - 'true':function(){return true;}, - 'false':function(){return false;}, - undefined:noop, - '+':function(self, locals, a,b){ - a=a(self, locals); b=b(self, locals); - if (isDefined(a)) { - if (isDefined(b)) { - return a + b; - } - return a; - } - return isDefined(b)?b:undefined;}, - '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, - '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, - '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, - '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, - '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, - '=':noop, - '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, - '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, - '<':function(self, locals, a,b){return a(self, locals)':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, - '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, - '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, - '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, - '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, - '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, -// '|':function(self, locals, a,b){return a|b;}, - '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));}, - '!':function(self, locals, a){return !a(self, locals);} -}; -var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; + /** + * @ngdoc function + * @name ng.$http + * @requires $httpBackend + * @requires $browser + * @requires $cacheFactory + * @requires $rootScope + * @requires $q + * @requires $injector + * + * @description + * The `$http` service is a core Angular service that facilitates communication with the remote + * HTTP servers via the browser's {@link https://developer.mozilla.org/en/xmlhttprequest + * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}. + * + * For unit testing applications that use `$http` service, see + * {@link ngMock.$httpBackend $httpBackend mock}. + * + * For a higher level of abstraction, please check out the {@link ngResource.$resource + * $resource} service. + * + * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by + * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage + * it is important to familiarize yourself with these APIs and the guarantees they provide. + * + * + * # General usage + * The `$http` service is a function which takes a single argument — a configuration object — + * that is used to generate an HTTP request and returns a {@link ng.$q promise} + * with two $http specific methods: `success` and `error`. + * + *
+     *   $http({method: 'GET', url: '/someUrl'}).
+     *     success(function(data, status, headers, config) {
+     *       // this callback will be called asynchronously
+     *       // when the response is available
+     *     }).
+     *     error(function(data, status, headers, config) {
+     *       // called asynchronously if an error occurs
+     *       // or server returns response with an error status.
+     *     });
+     * 
+ * + * Since the returned value of calling the $http function is a `promise`, you can also use + * the `then` method to register callbacks, and these callbacks will receive a single argument – + * an object representing the response. See the API signature and type info below for more + * details. + * + * A response status code between 200 and 299 is considered a success status and + * will result in the success callback being called. Note that if the response is a redirect, + * XMLHttpRequest will transparently follow it, meaning that the error callback will not be + * called for such responses. + * + * # Shortcut methods + * + * Since all invocations of the $http service require passing in an HTTP method and URL, and + * POST/PUT requests require request data to be provided as well, shortcut methods + * were created: + * + *
+     *   $http.get('/someUrl').success(successCallback);
+     *   $http.post('/someUrl', data).success(successCallback);
+     * 
+ * + * Complete list of shortcut methods: + * + * - {@link ng.$http#get $http.get} + * - {@link ng.$http#head $http.head} + * - {@link ng.$http#post $http.post} + * - {@link ng.$http#put $http.put} + * - {@link ng.$http#delete $http.delete} + * - {@link ng.$http#jsonp $http.jsonp} + * + * + * # Setting HTTP Headers + * + * The $http service will automatically add certain HTTP headers to all requests. These defaults + * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration + * object, which currently contains this default configuration: + * + * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): + * - `Accept: application/json, text/plain, * / *` + * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) + * - `Content-Type: application/json` + * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) + * - `Content-Type: application/json` + * + * To add or overwrite these defaults, simply add or remove a property from these configuration + * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object + * with the lowercased HTTP method name as the key, e.g. + * `$httpProvider.defaults.headers.get['My-Header']='value'`. + * + * Additionally, the defaults can be set at runtime via the `$http.defaults` object in the same + * fashion. + * + * + * # Transforming Requests and Responses + * + * Both requests and responses can be transformed using transform functions. By default, Angular + * applies these transformations: + * + * Request transformations: + * + * - If the `data` property of the request configuration object contains an object, serialize it into + * JSON format. + * + * Response transformations: + * + * - If XSRF prefix is detected, strip it (see Security Considerations section below). + * - If JSON response is detected, deserialize it using a JSON parser. + * + * To globally augment or override the default transforms, modify the `$httpProvider.defaults.transformRequest` and + * `$httpProvider.defaults.transformResponse` properties. These properties are by default an + * array of transform functions, which allows you to `push` or `unshift` a new transformation function into the + * transformation chain. You can also decide to completely override any default transformations by assigning your + * transformation functions to these properties directly without the array wrapper. + * + * Similarly, to locally override the request/response transforms, augment the `transformRequest` and/or + * `transformResponse` properties of the configuration object passed into `$http`. + * + * + * # Caching + * + * To enable caching, set the configuration property `cache` to `true`. When the cache is + * enabled, `$http` stores the response from the server in local cache. Next time the + * response is served from the cache without sending a request to the server. + * + * Note that even if the response is served from cache, delivery of the data is asynchronous in + * the same way that real requests are. + * + * If there are multiple GET requests for the same URL that should be cached using the same + * cache, but the cache is not populated yet, only one request to the server will be made and + * the remaining requests will be fulfilled using the response from the first request. + * + * A custom default cache built with $cacheFactory can be provided in $http.defaults.cache. + * To skip it, set configuration property `cache` to `false`. + * + * + * # Interceptors + * + * Before you start creating interceptors, be sure to understand the + * {@link ng.$q $q and deferred/promise APIs}. + * + * For purposes of global error handling, authentication, or any kind of synchronous or + * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be + * able to intercept requests before they are handed to the server and + * responses before they are handed over to the application code that + * initiated these requests. The interceptors leverage the {@link ng.$q + * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing. + * + * The interceptors are service factories that are registered with the `$httpProvider` by + * adding them to the `$httpProvider.interceptors` array. The factory is called and + * injected with dependencies (if specified) and returns the interceptor. + * + * There are two kinds of interceptors (and two kinds of rejection interceptors): + * + * * `request`: interceptors get called with http `config` object. The function is free to modify + * the `config` or create a new one. The function needs to return the `config` directly or as a + * promise. + * * `requestError`: interceptor gets called when a previous interceptor threw an error or resolved + * with a rejection. + * * `response`: interceptors get called with http `response` object. The function is free to modify + * the `response` or create a new one. The function needs to return the `response` directly or as a + * promise. + * * `responseError`: interceptor gets called when a previous interceptor threw an error or resolved + * with a rejection. + * + * + *
+     *   // register the interceptor as a service
+     *   $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
+     *     return {
+     *       // optional method
+     *       'request': function(config) {
+     *         // do something on success
+     *         return config || $q.when(config);
+     *       },
+     *
+     *       // optional method
+     *      'requestError': function(rejection) {
+     *         // do something on error
+     *         if (canRecover(rejection)) {
+     *           return responseOrNewPromise
+     *         }
+     *         return $q.reject(rejection);
+     *       },
+     *
+     *
+     *
+     *       // optional method
+     *       'response': function(response) {
+     *         // do something on success
+     *         return response || $q.when(response);
+     *       },
+     *
+     *       // optional method
+     *      'responseError': function(rejection) {
+     *         // do something on error
+     *         if (canRecover(rejection)) {
+     *           return responseOrNewPromise
+     *         }
+     *         return $q.reject(rejection);
+     *       };
+     *     }
+     *   });
+     *
+     *   $httpProvider.interceptors.push('myHttpInterceptor');
+     *
+     *
+     *   // register the interceptor via an anonymous factory
+     *   $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
+     *     return {
+     *      'request': function(config) {
+     *          // same as above
+     *       },
+     *       'response': function(response) {
+     *          // same as above
+     *       }
+     *   });
+     * 
+ * + * # Response interceptors (DEPRECATED) + * + * Before you start creating interceptors, be sure to understand the + * {@link ng.$q $q and deferred/promise APIs}. + * + * For purposes of global error handling, authentication or any kind of synchronous or + * asynchronous preprocessing of received responses, it is desirable to be able to intercept + * responses for http requests before they are handed over to the application code that + * initiated these requests. The response interceptors leverage the {@link ng.$q + * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. + * + * The interceptors are service factories that are registered with the $httpProvider by + * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and + * injected with dependencies (if specified) and returns the interceptor — a function that + * takes a {@link ng.$q promise} and returns the original or a new promise. + * + *
+     *   // register the interceptor as a service
+     *   $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
+     *     return function(promise) {
+     *       return promise.then(function(response) {
+     *         // do something on success
+     *       }, function(response) {
+     *         // do something on error
+     *         if (canRecover(response)) {
+     *           return responseOrNewPromise
+     *         }
+     *         return $q.reject(response);
+     *       });
+     *     }
+     *   });
+     *
+     *   $httpProvider.responseInterceptors.push('myHttpInterceptor');
+     *
+     *
+     *   // register the interceptor via an anonymous factory
+     *   $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
+     *     return function(promise) {
+     *       // same as above
+     *     }
+     *   });
+     * 
+ * + * + * # Security Considerations + * + * When designing web applications, consider security threats from: + * + * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx + * JSON vulnerability} + * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} + * + * Both server and the client must cooperate in order to eliminate these threats. Angular comes + * pre-configured with strategies that address these issues, but for this to work backend server + * cooperation is required. + * + * ## JSON Vulnerability Protection + * + * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx + * JSON vulnerability} allows third party website to turn your JSON resource URL into + * {@link http://en.wikipedia.org/wiki/JSONP JSONP} request under some conditions. To + * counter this your server can prefix all JSON requests with following string `")]}',\n"`. + * Angular will automatically strip the prefix before processing it as JSON. + * + * For example if your server needs to return: + *
+     * ['one','two']
+     * 
+ * + * which is vulnerable to attack, your server can return: + *
+     * )]}',
+     * ['one','two']
+     * 
+ * + * Angular will strip the prefix, before processing the JSON. + * + * + * ## Cross Site Request Forgery (XSRF) Protection + * + * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which + * an unauthorized site can gain your user's private data. Angular provides a mechanism + * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie + * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only + * JavaScript that runs on your domain could read the cookie, your server can be assured that + * the XHR came from JavaScript running on your domain. The header will not be set for + * cross-domain requests. + * + * To take advantage of this, your server needs to set a token in a JavaScript readable session + * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the + * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure + * that only JavaScript running on your domain could have sent the request. The token must be + * unique for each user and must be verifiable by the server (to prevent the JavaScript from making + * up its own tokens). We recommend that the token is a digest of your site's authentication + * cookie with a {@link https://en.wikipedia.org/wiki/Salt_(cryptography) salt} for added security. + * + * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName + * properties of either $httpProvider.defaults, or the per-request config object. + * + * + * @param {object} config Object describing the request to be made and how it should be + * processed. The object has following properties: + * + * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) + * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. + * - **params** – `{Object.}` – Map of strings or objects which will be turned to + * `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified. + * - **data** – `{string|Object}` – Data to be sent as the request message data. + * - **headers** – `{Object}` – Map of strings or functions which return strings representing + * HTTP headers to send to the server. If the return value of a function is null, the header will + * not be sent. + * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. + * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. + * - **transformRequest** – `{function(data, headersGetter)|Array.}` – + * transform function or an array of such functions. The transform function takes the http + * request body and headers and returns its transformed (typically serialized) version. + * - **transformResponse** – `{function(data, headersGetter)|Array.}` – + * transform function or an array of such functions. The transform function takes the http + * response body and headers and returns its transformed (typically deserialized) version. + * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the + * GET request, otherwise if a cache instance built with + * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for + * caching. + * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} + * that should abort the request when resolved. + * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the + * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 + * requests with credentials} for more information. + * - **responseType** - `{string}` - see {@link + * https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}. + * + * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the + * standard `then` method and two http specific methods: `success` and `error`. The `then` + * method takes two arguments a success and an error callback which will be called with a + * response object. The `success` and `error` methods take a single argument - a function that + * will be called when the request succeeds or fails respectively. The arguments passed into + * these functions are destructured representation of the response object passed into the + * `then` method. The response object has these properties: + * + * - **data** – `{string|Object}` – The response body transformed with the transform functions. + * - **status** – `{number}` – HTTP status code of the response. + * - **headers** – `{function([headerName])}` – Header getter function. + * - **config** – `{Object}` – The configuration object that was used to generate the request. + * + * @property {Array.} pendingRequests Array of config objects for currently pending + * requests. This is primarily meant to be used for debugging purposes. + * + * + * @example + + +
+ + +
+ + + +
http status code: {{status}}
+
http response data: {{data}}
+
+
+ + function FetchCtrl($scope, $http, $templateCache) { + $scope.method = 'GET'; + $scope.url = 'http-hello.html'; -function lex(text, csp){ - var tokens = [], - token, - index = 0, - json = [], - ch, - lastCh = ':'; // can start regexp + $scope.fetch = function() { + $scope.code = null; + $scope.response = null; - while (index < text.length) { - ch = text.charAt(index); - if (is('"\'')) { - readString(ch); - } else if (isNumber(ch) || is('.') && isNumber(peek())) { - readNumber(); - } else if (isIdent(ch)) { - readIdent(); - // identifiers can only be if the preceding char was a { or , - if (was('{,') && json[0]=='{' && - (token=tokens[tokens.length-1])) { - token.json = token.text.indexOf('.') == -1; - } - } else if (is('(){}[].,;:')) { - tokens.push({ - index:index, - text:ch, - json:(was(':[,') && is('{[')) || is('}]:,') - }); - if (is('{[')) json.unshift(ch); - if (is('}]')) json.shift(); - index++; - } else if (isWhitespace(ch)) { - index++; - continue; - } else { - var ch2 = ch + peek(), - fn = OPERATORS[ch], - fn2 = OPERATORS[ch2]; - if (fn2) { - tokens.push({index:index, text:ch2, fn:fn2}); - index += 2; - } else if (fn) { - tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); - index += 1; - } else { - throwError("Unexpected next character ", index, index+1); - } - } - lastCh = ch; - } - return tokens; + $http({method: $scope.method, url: $scope.url, cache: $templateCache}). + success(function(data, status) { + $scope.status = status; + $scope.data = data; + }). + error(function(data, status) { + $scope.data = data || "Request failed"; + $scope.status = status; + }); + }; - function is(chars) { - return chars.indexOf(ch) != -1; - } + $scope.updateModel = function(method, url) { + $scope.method = method; + $scope.url = url; + }; + } + + + Hello, $http! + + + it('should make an xhr GET request', function() { + element(':button:contains("Sample GET")').click(); + element(':button:contains("fetch")').click(); + expect(binding('status')).toBe('200'); + expect(binding('data')).toMatch(/Hello, \$http!/); + }); - function was(chars) { - return chars.indexOf(lastCh) != -1; - } + it('should make a JSONP request to angularjs.org', function() { + element(':button:contains("Sample JSONP")').click(); + element(':button:contains("fetch")').click(); + expect(binding('status')).toBe('200'); + expect(binding('data')).toMatch(/Super Hero!/); + }); - function peek() { - return index + 1 < text.length ? text.charAt(index + 1) : false; - } - function isNumber(ch) { - return '0' <= ch && ch <= '9'; - } - function isWhitespace(ch) { - return ch == ' ' || ch == '\r' || ch == '\t' || - ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 - } - function isIdent(ch) { - return 'a' <= ch && ch <= 'z' || - 'A' <= ch && ch <= 'Z' || - '_' == ch || ch == '$'; - } - function isExpOperator(ch) { - return ch == '-' || ch == '+' || isNumber(ch); - } + it('should make JSONP request to invalid URL and invoke the error handler', + function() { + element(':button:contains("Invalid JSONP")').click(); + element(':button:contains("fetch")').click(); + expect(binding('status')).toBe('0'); + expect(binding('data')).toBe('Request failed'); + }); + +
+ */ + function $http(requestConfig) { + var config = { + transformRequest: defaults.transformRequest, + transformResponse: defaults.transformResponse + }; + var headers = mergeHeaders(requestConfig); - function throwError(error, start, end) { - end = end || index; - throw Error("Lexer Error: " + error + " at column" + - (isDefined(start) - ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]" - : " " + end) + - " in expression [" + text + "]."); - } + extend(config, requestConfig); + config.headers = headers; + config.method = uppercase(config.method); - function readNumber() { - var number = ""; - var start = index; - while (index < text.length) { - var ch = lowercase(text.charAt(index)); - if (ch == '.' || isNumber(ch)) { - number += ch; - } else { - var peekCh = peek(); - if (ch == 'e' && isExpOperator(peekCh)) { - number += ch; - } else if (isExpOperator(ch) && - peekCh && isNumber(peekCh) && - number.charAt(number.length - 1) == 'e') { - number += ch; - } else if (isExpOperator(ch) && - (!peekCh || !isNumber(peekCh)) && - number.charAt(number.length - 1) == 'e') { - throwError('Invalid exponent'); - } else { - break; - } + var xsrfValue = $$urlUtils.isSameOrigin(config.url) + ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] + : undefined; + if (xsrfValue) { + headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; } - index++; - } - number = 1 * number; - tokens.push({index:start, text:number, json:true, - fn:function() {return number;}}); - } - function readIdent() { - var ident = "", - start = index, - lastDot, peekIndex, methodName, ch; - while (index < text.length) { - ch = text.charAt(index); - if (ch == '.' || isIdent(ch) || isNumber(ch)) { - if (ch == '.') lastDot = index; - ident += ch; - } else { - break; - } - index++; - } - //check if this is not a method invocation and if it is back out to last dot - if (lastDot) { - peekIndex = index; - while(peekIndex < text.length) { - ch = text.charAt(peekIndex); - if (ch == '(') { - methodName = ident.substr(lastDot - start + 1); - ident = ident.substr(0, lastDot - start); - index = peekIndex; - break; + var serverRequest = function(config) { + headers = config.headers; + var reqData = transformData(config.data, headersGetter(headers), config.transformRequest); + + // strip content-type if data is undefined + if (isUndefined(config.data)) { + forEach(headers, function(value, header) { + if (lowercase(header) === 'content-type') { + delete headers[header]; + } + }); } - if(isWhitespace(ch)) { - peekIndex++; - } else { - break; + + if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { + config.withCredentials = defaults.withCredentials; } - } - } + // send request + return sendReq(config, reqData, headers).then(transformResponse, transformResponse); + }; - var token = { - index:start, - text:ident - }; + var chain = [serverRequest, undefined]; + var promise = $q.when(config); - if (OPERATORS.hasOwnProperty(ident)) { - token.fn = token.json = OPERATORS[ident]; - } else { - var getter = getterFn(ident, csp); - token.fn = extend(function(self, locals) { - return (getter(self, locals)); - }, { - assign: function(self, value) { - return setter(self, ident, value); + // apply interceptors + forEach(reversedInterceptors, function(interceptor) { + if (interceptor.request || interceptor.requestError) { + chain.unshift(interceptor.request, interceptor.requestError); + } + if (interceptor.response || interceptor.responseError) { + chain.push(interceptor.response, interceptor.responseError); } }); - } - tokens.push(token); + while(chain.length) { + var thenFn = chain.shift(); + var rejectFn = chain.shift(); - if (methodName) { - tokens.push({ - index:lastDot, - text: '.', - json: false - }); - tokens.push({ - index: lastDot + 1, - text: methodName, - json: false - }); - } - } + promise = promise.then(thenFn, rejectFn); + } - function readString(quote) { - var start = index; - index++; - var string = ""; - var rawString = quote; - var escape = false; - while (index < text.length) { - var ch = text.charAt(index); - rawString += ch; - if (escape) { - if (ch == 'u') { - var hex = text.substring(index + 1, index + 5); - if (!hex.match(/[\da-f]{4}/i)) - throwError( "Invalid unicode escape [\\u" + hex + "]"); - index += 4; - string += String.fromCharCode(parseInt(hex, 16)); - } else { - var rep = ESCAPE[ch]; - if (rep) { - string += rep; - } else { - string += ch; - } - } - escape = false; - } else if (ch == '\\') { - escape = true; - } else if (ch == quote) { - index++; - tokens.push({ - index:start, - text:rawString, - string:string, - json:true, - fn:function() { return string; } + promise.success = function(fn) { + promise.then(function(response) { + fn(response.data, response.status, response.headers, config); }); - return; - } else { - string += ch; - } - index++; - } - throwError("Unterminated quote", start); - } -} + return promise; + }; + + promise.error = function(fn) { + promise.then(null, function(response) { + fn(response.data, response.status, response.headers, config); + }); + return promise; + }; -///////////////////////////////////////// + return promise; -function parser(text, json, $filter, csp){ - var ZERO = valueFn(0), - value, - tokens = lex(text, csp), - assignment = _assignment, - functionCall = _functionCall, - fieldAccess = _fieldAccess, - objectIndex = _objectIndex, - filterChain = _filterChain; + function transformResponse(response) { + // make a copy since the response must be cacheable + var resp = extend({}, response, { + data: transformData(response.data, response.headers, config.transformResponse) + }); + return (isSuccess(response.status)) + ? resp + : $q.reject(resp); + } - if(json){ - // The extra level of aliasing is here, just in case the lexer misses something, so that - // we prevent any accidental execution in JSON. - assignment = logicalOR; - functionCall = - fieldAccess = - objectIndex = - filterChain = - function() { throwError("is not valid json", {text:text, index:0}); }; - value = primary(); - } else { - value = statements(); - } - if (tokens.length !== 0) { - throwError("is an unexpected token", tokens[0]); - } - return value; + function mergeHeaders(config) { + var defHeaders = defaults.headers, + reqHeaders = extend({}, config.headers), + defHeaderName, lowercaseDefHeaderName, reqHeaderName; - /////////////////////////////////// - function throwError(msg, token) { - throw Error("Syntax Error: Token '" + token.text + - "' " + msg + " at column " + - (token.index + 1) + " of the expression [" + - text + "] starting at [" + text.substring(token.index) + "]."); - } + defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); - function peekToken() { - if (tokens.length === 0) - throw Error("Unexpected end of expression: " + text); - return tokens[0]; - } + // execute if header value is function + execHeaders(defHeaders); + execHeaders(reqHeaders); - function peek(e1, e2, e3, e4) { - if (tokens.length > 0) { - var token = tokens[0]; - var t = token.text; - if (t==e1 || t==e2 || t==e3 || t==e4 || - (!e1 && !e2 && !e3 && !e4)) { - return token; - } - } - return false; - } + // using for-in instead of forEach to avoid unecessary iteration after header has been found + defaultHeadersIteration: + for (defHeaderName in defHeaders) { + lowercaseDefHeaderName = lowercase(defHeaderName); - function expect(e1, e2, e3, e4){ - var token = peek(e1, e2, e3, e4); - if (token) { - if (json && !token.json) { - throwError("is not valid json", token); - } - tokens.shift(); - return token; - } - return false; - } + for (reqHeaderName in reqHeaders) { + if (lowercase(reqHeaderName) === lowercaseDefHeaderName) { + continue defaultHeadersIteration; + } + } - function consume(e1){ - if (!expect(e1)) { - throwError("is unexpected, expecting [" + e1 + "]", peek()); - } - } + reqHeaders[defHeaderName] = defHeaders[defHeaderName]; + } - function unaryFn(fn, right) { - return function(self, locals) { - return fn(self, locals, right); - }; - } + return reqHeaders; - function binaryFn(left, fn, right) { - return function(self, locals) { - return fn(self, locals, left, right); - }; - } + function execHeaders(headers) { + var headerContent; - function statements() { - var statements = []; - while(true) { - if (tokens.length > 0 && !peek('}', ')', ';', ']')) - statements.push(filterChain()); - if (!expect(';')) { - // optimize for the common case where there is only one statement. - // TODO(size): maybe we should not support multiple statements? - return statements.length == 1 - ? statements[0] - : function(self, locals){ - var value; - for ( var i = 0; i < statements.length; i++) { - var statement = statements[i]; - if (statement) - value = statement(self, locals); + forEach(headers, function(headerFn, header) { + if (isFunction(headerFn)) { + headerContent = headerFn(); + if (headerContent != null) { + headers[header] = headerContent; + } else { + delete headers[header]; + } } - return value; - }; + }); + } } } - } - function _filterChain() { - var left = expression(); - var token; - while(true) { - if ((token = expect('|'))) { - left = binaryFn(left, token.fn, filter()); - } else { - return left; - } - } - } + $http.pendingRequests = []; - function filter() { - var token = expect(); - var fn = $filter(token.text); - var argsFn = []; - while(true) { - if ((token = expect(':'))) { - argsFn.push(expression()); - } else { - var fnInvoke = function(self, locals, input){ - var args = [input]; - for ( var i = 0; i < argsFn.length; i++) { - args.push(argsFn[i](self, locals)); - } - return fn.apply(self, args); - }; - return function() { - return fnInvoke; - }; - } - } - } + /** + * @ngdoc method + * @name ng.$http#get + * @methodOf ng.$http + * + * @description + * Shortcut method to perform `GET` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ - function expression() { - return assignment(); - } + /** + * @ngdoc method + * @name ng.$http#delete + * @methodOf ng.$http + * + * @description + * Shortcut method to perform `DELETE` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ - function _assignment() { - var left = logicalOR(); - var right; - var token; - if ((token = expect('='))) { - if (!left.assign) { - throwError("implies assignment but [" + - text.substring(0, token.index) + "] can not be assigned to", token); - } - right = logicalOR(); - return function(scope, locals){ - return left.assign(scope, right(scope, locals), locals); - }; - } else { - return left; - } - } + /** + * @ngdoc method + * @name ng.$http#head + * @methodOf ng.$http + * + * @description + * Shortcut method to perform `HEAD` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ - function logicalOR() { - var left = logicalAND(); - var token; - while(true) { - if ((token = expect('||'))) { - left = binaryFn(left, token.fn, logicalAND()); - } else { - return left; - } - } - } + /** + * @ngdoc method + * @name ng.$http#jsonp + * @methodOf ng.$http + * + * @description + * Shortcut method to perform `JSONP` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request. + * Should contain `JSON_CALLBACK` string. + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + createShortMethods('get', 'delete', 'head', 'jsonp'); + + /** + * @ngdoc method + * @name ng.$http#post + * @methodOf ng.$http + * + * @description + * Shortcut method to perform `POST` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {*} data Request content + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name ng.$http#put + * @methodOf ng.$http + * + * @description + * Shortcut method to perform `PUT` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {*} data Request content + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + createShortMethodsWithData('post', 'put'); + + /** + * @ngdoc property + * @name ng.$http#defaults + * @propertyOf ng.$http + * + * @description + * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of + * default headers, withCredentials as well as request and response transformations. + * + * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. + */ + $http.defaults = defaults; - function logicalAND() { - var left = equality(); - var token; - if ((token = expect('&&'))) { - left = binaryFn(left, token.fn, logicalAND()); - } - return left; - } - function equality() { - var left = relational(); - var token; - if ((token = expect('==','!='))) { - left = binaryFn(left, token.fn, equality()); - } - return left; - } + return $http; - function relational() { - var left = additive(); - var token; - if ((token = expect('<', '>', '<=', '>='))) { - left = binaryFn(left, token.fn, relational()); - } - return left; - } - function additive() { - var left = multiplicative(); - var token; - while ((token = expect('+','-'))) { - left = binaryFn(left, token.fn, multiplicative()); + function createShortMethods(names) { + forEach(arguments, function(name) { + $http[name] = function(url, config) { + return $http(extend(config || {}, { + method: name, + url: url + })); + }; + }); } - return left; - } - function multiplicative() { - var left = unary(); - var token; - while ((token = expect('*','/','%'))) { - left = binaryFn(left, token.fn, unary()); - } - return left; - } - function unary() { - var token; - if (expect('+')) { - return primary(); - } else if ((token = expect('-'))) { - return binaryFn(ZERO, token.fn, unary()); - } else if ((token = expect('!'))) { - return unaryFn(token.fn, unary()); - } else { - return primary(); + function createShortMethodsWithData(name) { + forEach(arguments, function(name) { + $http[name] = function(url, data, config) { + return $http(extend(config || {}, { + method: name, + url: url, + data: data + })); + }; + }); } - } - function primary() { - var primary; - if (expect('(')) { - primary = filterChain(); - consume(')'); - } else if (expect('[')) { - primary = arrayDeclaration(); - } else if (expect('{')) { - primary = object(); - } else { - var token = expect(); - primary = token.fn; - if (!primary) { - throwError("not a primary expression", token); - } - } + /** + * Makes the request. + * + * !!! ACCESSES CLOSURE VARS: + * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests + */ + function sendReq(config, reqData, reqHeaders) { + var deferred = $q.defer(), + promise = deferred.promise, + cache, + cachedResp, + url = buildUrl(config.url, config.params); - var next, context; - while ((next = expect('(', '[', '.'))) { - if (next.text === '(') { - primary = functionCall(primary, context); - context = null; - } else if (next.text === '[') { - context = primary; - primary = objectIndex(primary); - } else if (next.text === '.') { - context = primary; - primary = fieldAccess(primary); - } else { - throwError("IMPOSSIBLE"); + $http.pendingRequests.push(config); + promise.then(removePendingReq, removePendingReq); + + + if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') { + cache = isObject(config.cache) ? config.cache + : isObject(defaults.cache) ? defaults.cache + : defaultCache; } - } - return primary; - } - function _fieldAccess(object) { - var field = expect().text; - var getter = getterFn(field, csp); - return extend( - function(scope, locals, self) { - return getter(self || object(scope, locals), locals); - }, - { - assign:function(scope, value, locals) { - return setter(object(scope, locals), field, value); + if (cache) { + cachedResp = cache.get(url); + if (cachedResp) { + if (cachedResp.then) { + // cached request has already been sent, but there is no response yet + cachedResp.then(removePendingReq, removePendingReq); + return cachedResp; + } else { + // serving from cache + if (isArray(cachedResp)) { + resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2])); + } else { + resolvePromise(cachedResp, 200, {}); + } } + } else { + // put the promise for the non-transformed response into cache as a placeholder + cache.put(url, promise); } - ); - } + } - function _objectIndex(obj) { - var indexFn = expression(); - consume(']'); - return extend( - function(self, locals){ - var o = obj(self, locals), - i = indexFn(self, locals), - v, p; + // if we won't have the response in cache, send the request to the backend + if (!cachedResp) { + $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, + config.withCredentials, config.responseType); + } - if (!o) return undefined; - v = o[i]; - if (v && v.then) { - p = v; - if (!('$$v' in v)) { - p.$$v = undefined; - p.then(function(val) { p.$$v = val; }); + return promise; + + + /** + * Callback registered to $httpBackend(): + * - caches the response if desired + * - resolves the raw $http promise + * - calls $apply + */ + function done(status, response, headersString) { + if (cache) { + if (isSuccess(status)) { + cache.put(url, [status, response, parseHeaders(headersString)]); + } else { + // remove promise from the cache + cache.remove(url); } - v = v.$$v; - } - return v; - }, { - assign:function(self, value, locals){ - return obj(self, locals)[indexFn(self, locals)] = value; } - }); - } - - function _functionCall(fn, contextGetter) { - var argsFn = []; - if (peekToken().text != ')') { - do { - argsFn.push(expression()); - } while (expect(',')); - } - consume(')'); - return function(scope, locals){ - var args = [], - context = contextGetter ? contextGetter(scope, locals) : scope; - for ( var i = 0; i < argsFn.length; i++) { - args.push(argsFn[i](scope, locals)); + resolvePromise(response, status, headersString); + if (!$rootScope.$$phase) $rootScope.$apply(); } - var fnPtr = fn(scope, locals, context) || noop; - // IE stupidity! - return fnPtr.apply - ? fnPtr.apply(context, args) - : fnPtr(args[0], args[1], args[2], args[3], args[4]); - }; - } - // This is used with json array declaration - function arrayDeclaration () { - var elementFns = []; - if (peekToken().text != ']') { - do { - elementFns.push(expression()); - } while (expect(',')); - } - consume(']'); - return function(self, locals){ - var array = []; - for ( var i = 0; i < elementFns.length; i++) { - array.push(elementFns[i](self, locals)); - } - return array; - }; - } - function object () { - var keyValues = []; - if (peekToken().text != '}') { - do { - var token = expect(), - key = token.string || token.text; - consume(":"); - var value = expression(); - keyValues.push({key:key, value:value}); - } while (expect(',')); - } - consume('}'); - return function(self, locals){ - var object = {}; - for ( var i = 0; i < keyValues.length; i++) { - var keyValue = keyValues[i]; - object[keyValue.key] = keyValue.value(self, locals); + /** + * Resolves the raw $http promise. + */ + function resolvePromise(response, status, headers) { + // normalize internal statuses to 0 + status = Math.max(status, 0); + + (isSuccess(status) ? deferred.resolve : deferred.reject)({ + data: response, + status: status, + headers: headersGetter(headers), + config: config + }); } - return object; - }; - } -} -////////////////////////////////////////////////// -// Parser helper functions -////////////////////////////////////////////////// -function setter(obj, path, setValue) { - var element = path.split('.'); - for (var i = 0; element.length > 1; i++) { - var key = element.shift(); - var propertyObj = obj[key]; - if (!propertyObj) { - propertyObj = {}; - obj[key] = propertyObj; + function removePendingReq() { + var idx = indexOf($http.pendingRequests, config); + if (idx !== -1) $http.pendingRequests.splice(idx, 1); + } } - obj = propertyObj; - } - obj[element.shift()] = setValue; - return setValue; -} -/** - * Return the value accesible from the object by path. Any undefined traversals are ignored - * @param {Object} obj starting object - * @param {string} path path to traverse - * @param {boolean=true} bindFnToScope - * @returns value as accesbile by path - */ -//TODO(misko): this function needs to be removed -function getter(obj, path, bindFnToScope) { - if (!path) return obj; - var keys = path.split('.'); - var key; - var lastInstance = obj; - var len = keys.length; - for (var i = 0; i < len; i++) { - key = keys[i]; - if (obj) { - obj = (lastInstance = obj)[key]; - } - } - if (!bindFnToScope && isFunction(obj)) { - return bind(lastInstance, obj); - } - return obj; + function buildUrl(url, params) { + if (!params) return url; + var parts = []; + forEachSorted(params, function(value, key) { + if (value == null || value == undefined) return; + if (!isArray(value)) value = [value]; + + forEach(value, function(v) { + if (isObject(v)) { + v = toJson(v); + } + parts.push(encodeUriQuery(key) + '=' + + encodeUriQuery(v)); + }); + }); + return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); + } + + + }]; } -var getterFnCache = {}; +var XHR = window.XMLHttpRequest || function() { + try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} + try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} + try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} + throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest."); +}; + /** - * Implementation of the "Black Hole" variant from: - * - http://jsperf.com/angularjs-parse-getter/4 - * - http://jsperf.com/path-evaluation-simplified/7 + * @ngdoc object + * @name ng.$httpBackend + * @requires $browser + * @requires $window + * @requires $document + * + * @description + * HTTP backend used by the {@link ng.$http service} that delegates to + * 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 ng.$http $http} or {@link ngResource.$resource $resource}. + * + * During testing this implementation is swapped with {@link ngMock.$httpBackend mock + * $httpBackend} which can be trained with responses. */ -function cspSafeGetterFn(key0, key1, key2, key3, key4) { - return function(scope, locals) { - var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, - promise; +function $HttpBackendProvider() { + this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { + return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks, + $document[0], $window.location.protocol.replace(':', '')); + }]; +} - if (pathVal === null || pathVal === undefined) return pathVal; +function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) { + // TODO(vojta): fix the signature + return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { + var status; + $browser.$$incOutstandingRequestCount(); + url = url || $browser.url(); - pathVal = pathVal[key0]; - if (pathVal && pathVal.then) { - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - if (!key1 || pathVal === null || pathVal === undefined) return pathVal; + if (lowercase(method) == 'jsonp') { + var callbackId = '_' + (callbacks.counter++).toString(36); + callbacks[callbackId] = function(data) { + callbacks[callbackId].data = data; + }; - pathVal = pathVal[key1]; - if (pathVal && pathVal.then) { - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); + var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), + function() { + if (callbacks[callbackId].data) { + completeRequest(callback, 200, callbacks[callbackId].data); + } else { + completeRequest(callback, status || -2); + } + delete callbacks[callbackId]; + }); + } else { + var xhr = new XHR(); + xhr.open(method, url, true); + forEach(headers, function(value, key) { + if (value) xhr.setRequestHeader(key, value); + }); + + // In IE6 and 7, this might be called synchronously when xhr.send below is called and the + // response is in the cache. the promise api will ensure that to the app code the api is + // always async + xhr.onreadystatechange = function() { + if (xhr.readyState == 4) { + var responseHeaders = xhr.getAllResponseHeaders(); + + // TODO(vojta): remove once Firefox 21 gets released. + // begin: workaround to overcome Firefox CORS http response headers bug + // https://bugzilla.mozilla.org/show_bug.cgi?id=608735 + // Firefox already patched in nightly. Should land in Firefox 21. + + // CORS "simple response headers" http://www.w3.org/TR/cors/ + var value, + simpleHeaders = ["Cache-Control", "Content-Language", "Content-Type", + "Expires", "Last-Modified", "Pragma"]; + if (!responseHeaders) { + responseHeaders = ""; + forEach(simpleHeaders, function (header) { + var value = xhr.getResponseHeader(header); + if (value) { + responseHeaders += header + ": " + value + "\n"; + } + }); + } + // end of the workaround. + + // responseText is the old-school way of retrieving response (supported by IE8 & 9) + // response and responseType properties were introduced in XHR Level2 spec (supported by IE10) + completeRequest(callback, + status || xhr.status, + (xhr.responseType ? xhr.response : xhr.responseText), + responseHeaders); + } + }; + + if (withCredentials) { + xhr.withCredentials = true; } - pathVal = pathVal.$$v; - } - if (!key2 || pathVal === null || pathVal === undefined) return pathVal; - pathVal = pathVal[key2]; - if (pathVal && pathVal.then) { - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); + if (responseType) { + xhr.responseType = responseType; } - pathVal = pathVal.$$v; + + xhr.send(post || ''); } - if (!key3 || pathVal === null || pathVal === undefined) return pathVal; - pathVal = pathVal[key3]; - if (pathVal && pathVal.then) { - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; + if (timeout > 0) { + var timeoutId = $browserDefer(timeoutRequest, timeout); + } else if (timeout && timeout.then) { + timeout.then(timeoutRequest); } - if (!key4 || pathVal === null || pathVal === undefined) return pathVal; - pathVal = pathVal[key4]; - if (pathVal && pathVal.then) { - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; + + function timeoutRequest() { + status = -1; + jsonpDone && jsonpDone(); + xhr && xhr.abort(); } - return pathVal; - }; -} -function getterFn(path, csp) { - if (getterFnCache.hasOwnProperty(path)) { - return getterFnCache[path]; - } + function completeRequest(callback, status, response, headersString) { + // URL_MATCH is defined in src/service/location.js + var protocol = (url.match(SERVER_MATCH) || ['', locationProtocol])[1]; - var pathKeys = path.split('.'), - pathKeysLength = pathKeys.length, - fn; + // cancel timeout and subsequent timeout promise resolution + timeoutId && $browserDefer.cancel(timeoutId); + jsonpDone = xhr = null; - if (csp) { - fn = (pathKeysLength < 6) - ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4]) - : function(scope, locals) { - var i = 0, val; - do { - val = cspSafeGetterFn( - pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++] - )(scope, locals); + // fix status code for file protocol (it's always 0) + status = (protocol == 'file') ? (response ? 200 : 404) : status; - locals = undefined; // clear after first iteration - scope = val; - } while (i < pathKeysLength); - return val; - } - } else { - var code = 'var l, fn, p;\n'; - forEach(pathKeys, function(key, index) { - code += 'if(s === null || s === undefined) return s;\n' + - 'l=s;\n' + - 's='+ (index - // we simply dereference 's' on any .dot notation - ? 's' - // but if we are first then we check locals first, and if so read it first - : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' + - 'if (s && s.then) {\n' + - ' if (!("$$v" in s)) {\n' + - ' p=s;\n' + - ' p.$$v = undefined;\n' + - ' p.then(function(v) {p.$$v=v;});\n' + - '}\n' + - ' s=s.$$v\n' + - '}\n'; - }); - code += 'return s;'; - fn = Function('s', 'k', code); // s=scope, k=locals - fn.toString = function() { return code; }; - } + // normalize IE bug (http://bugs.jquery.com/ticket/1450) + status = status == 1223 ? 204 : status; + + callback(status, response, headersString); + $browser.$$completeOutstandingRequest(noop); + } + }; + + function jsonpReq(url, done) { + // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: + // - fetches local scripts via XHR and evals them + // - adds and immediately removes script elements from the document + var script = rawDocument.createElement('script'), + doneWrapper = function() { + rawDocument.body.removeChild(script); + if (done) done(); + }; + + script.type = 'text/javascript'; + script.src = url; - return getterFnCache[path] = fn; + if (msie) { + script.onreadystatechange = function() { + if (/loaded|complete/.test(script.readyState)) doneWrapper(); + }; + } else { + script.onload = script.onerror = doneWrapper; + } + + rawDocument.body.appendChild(script); + return doneWrapper; + } } -/////////////////////////////////// +var $interpolateMinErr = minErr('$interpolate'); /** - * @ngdoc function - * @name ng.$parse + * @ngdoc object + * @name ng.$interpolateProvider * @function * * @description * - * Converts Angular {@link guide/expression expression} into a function. - * - *
- *   var getter = $parse('user.name');
- *   var setter = getter.assign;
- *   var context = {user:{name:'angular'}};
- *   var locals = {user:{name:'local'}};
- *
- *   expect(getter(context)).toEqual('angular');
- *   setter(context, 'newValue');
- *   expect(context.user.name).toEqual('newValue');
- *   expect(getter(context, locals)).toEqual('local');
- * 
- * - * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (tipically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - * - * The return function also has an `assign` property, if the expression is assignable, which - * allows one to set values to expressions. - * + * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. + * + * @example + + + +
+ //label// +
+
+
*/ -function $ParseProvider() { - var cache = {}; - this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { - return function(exp) { - switch(typeof exp) { - case 'string': - return cache.hasOwnProperty(exp) - ? cache[exp] - : cache[exp] = parser(exp, false, $filter, $sniffer.csp); - case 'function': - return exp; - default: - return noop; - } - }; - }]; -} +function $InterpolateProvider() { + var startSymbol = '{{'; + var endSymbol = '}}'; -/** - * @ngdoc service - * @name ng.$q - * @requires $rootScope - * - * @description - * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). - * - * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an - * interface for interacting with an object that represents the result of an action that is - * performed asynchronously, and may or may not be finished at any given point in time. - * - * From the perspective of dealing with error handling, deferred and promise APIs are to - * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. - * - *
- *   // for the purpose of this example let's assume that variables `$q` and `scope` are
- *   // available in the current lexical scope (they could have been injected or passed in).
- *
- *   function asyncGreet(name) {
- *     var deferred = $q.defer();
- *
- *     setTimeout(function() {
- *       // since this fn executes async in a future turn of the event loop, we need to wrap
- *       // our code into an $apply call so that the model changes are properly observed.
- *       scope.$apply(function() {
- *         if (okToGreet(name)) {
- *           deferred.resolve('Hello, ' + name + '!');
- *         } else {
- *           deferred.reject('Greeting ' + name + ' is not allowed.');
- *         }
- *       });
- *     }, 1000);
- *
- *     return deferred.promise;
- *   }
- *
- *   var promise = asyncGreet('Robin Hood');
- *   promise.then(function(greeting) {
- *     alert('Success: ' + greeting);
- *   }, function(reason) {
- *     alert('Failed: ' + reason);
- *   });
- * 
- * - * At first it might not be obvious why this extra complexity is worth the trouble. The payoff - * comes in the way of - * [guarantees that promise and deferred APIs make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md). - * - * Additionally the promise api allows for composition that is very hard to do with the - * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. - * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the - * section on serial or parallel joining of promises. - * - * - * # The Deferred API - * - * A new instance of deferred is constructed by calling `$q.defer()`. - * - * The purpose of the deferred object is to expose the associated Promise instance as well as APIs - * that can be used for signaling the successful or unsuccessful completion of the task. - * - * **Methods** - * - * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection - * constructed via `$q.reject`, the promise will be rejected instead. - * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to - * resolving it with a rejection constructed via `$q.reject`. - * - * **Properties** - * - * - promise – `{Promise}` – promise object associated with this deferred. - * - * - * # The Promise API - * - * A new promise instance is created when a deferred instance is created and can be retrieved by - * calling `deferred.promise`. - * - * The purpose of the promise object is to allow for interested parties to get access to the result - * of the deferred task when it completes. - * - * **Methods** - * - * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved - * or rejected calls one of the success or error callbacks asynchronously as soon as the result - * is available. The callbacks are called with a single argument the result or rejection reason. - * - * This method *returns a new promise* which is resolved or rejected via the return value of the - * `successCallback` or `errorCallback`. - * - * - * # Chaining promises - * - * Because calling `then` api of a promise returns a new derived promise, it is easily possible - * to create a chain of promises: - * - *
- *   promiseB = promiseA.then(function(result) {
- *     return result + 1;
- *   });
- *
- *   // promiseB will be resolved immediately after promiseA is resolved and its value will be
- *   // the result of promiseA incremented by 1
- * 
- * - * It is possible to create chains of any length and since a promise can be resolved with another - * promise (which will defer its resolution further), it is possible to pause/defer resolution of - * the promises at any point in the chain. This makes it possible to implement powerful apis like - * $http's response interceptors. - * - * - * # Differences between Kris Kowal's Q and $q + /** + * @ngdoc method + * @name ng.$interpolateProvider#startSymbol + * @methodOf ng.$interpolateProvider + * @description + * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. + * + * @param {string=} value new value to set the starting symbol to. + * @returns {string|self} Returns the symbol when used as getter and self if used as setter. + */ + this.startSymbol = function(value){ + if (value) { + startSymbol = value; + return this; + } else { + return startSymbol; + } + }; + + /** + * @ngdoc method + * @name ng.$interpolateProvider#endSymbol + * @methodOf ng.$interpolateProvider + * @description + * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. + * + * @param {string=} value new value to set the ending symbol to. + * @returns {string|self} Returns the symbol when used as getter and self if used as setter. + */ + this.endSymbol = function(value){ + if (value) { + endSymbol = value; + return this; + } else { + return endSymbol; + } + }; + + + this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) { + var startSymbolLength = startSymbol.length, + endSymbolLength = endSymbol.length; + + /** + * @ngdoc function + * @name ng.$interpolate + * @function + * + * @requires $parse + * @requires $sce + * + * @description + * + * Compiles a string with markup into an interpolation function. This service is used by the + * HTML {@link ng.$compile $compile} service for data binding. See + * {@link ng.$interpolateProvider $interpolateProvider} for configuring the + * interpolation markup. + * + * +
+         var $interpolate = ...; // injected
+         var exp = $interpolate('Hello {{name}}!');
+         expect(exp({name:'Angular'}).toEqual('Hello Angular!');
+       
+ * + * + * @param {string} text The text with markup to interpolate. + * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have + * embedded expression in order to return an interpolation function. Strings with no + * embedded expression will return null for the interpolation function. + * @param {string=} trustedContext when provided, the returned function passes the interpolated + * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult, + * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that + * provides Strict Contextual Escaping for details. + * @returns {function(context)} an interpolation function which is used to compute the interpolated + * string. The function has these parameters: + * + * * `context`: an object against which any expressions embedded in the strings are evaluated + * against. + * + */ + function $interpolate(text, mustHaveExpression, trustedContext) { + var startIndex, + endIndex, + index = 0, + parts = [], + length = text.length, + hasInterpolation = false, + fn, + exp, + concat = []; + + while(index < length) { + if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && + ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { + (index != startIndex) && parts.push(text.substring(index, startIndex)); + parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex))); + fn.exp = exp; + index = endIndex + endSymbolLength; + hasInterpolation = true; + } else { + // we did not find anything, so we have to add the remainder to the parts array + (index != length) && parts.push(text.substring(index)); + index = length; + } + } + + if (!(length = parts.length)) { + // we added, nothing, must have been an empty string. + parts.push(''); + length = 1; + } + + // Concatenating expressions makes it hard to reason about whether some combination of concatenated + // values are unsafe to use and could easily lead to XSS. By requiring that a single + // expression be used for iframe[src], object[src], etc., we ensure that the value that's used + // is assigned or constructed by some JS code somewhere that is more testable or make it + // obvious that you bound the value to some user controlled value. This helps reduce the load + // when auditing for XSS issues. + if (trustedContext && parts.length > 1) { + throw $interpolateMinErr('noconcat', + "Error while interpolating: {0}\nStrict Contextual Escaping disallows " + + "interpolations that concatenate multiple expressions when a trusted value is " + + "required. See http://docs.angularjs.org/api/ng.$sce", text); + } + + if (!mustHaveExpression || hasInterpolation) { + concat.length = length; + fn = function(context) { + try { + for(var i = 0, ii = length, part; i - * it('should simulate promise', inject(function($q, $rootScope) { - * var deferred = $q.defer(); - * var promise = deferred.promise; - * var resolvedValue; - * - * promise.then(function(value) { resolvedValue = value; }); - * expect(resolvedValue).toBeUndefined(); - * - * // Simulate resolving of promise - * deferred.resolve(123); - * // Note that the 'then' function does not get called synchronously. - * // This is because we want the promise API to always be async, whether or not - * // it got called synchronously or asynchronously. - * expect(resolvedValue).toBeUndefined(); - * - * // Propagate promise resolution to 'then' functions using $apply(). - * $rootScope.$apply(); - * expect(resolvedValue).toEqual(123); - * }); - * + * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) */ -function $QProvider() { +function $LocaleProvider(){ + this.$get = function() { + return { + id: 'en-us', - this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { - return qFactory(function(callback) { - $rootScope.$evalAsync(callback); - }, $exceptionHandler); - }]; + NUMBER_FORMATS: { + DECIMAL_SEP: '.', + GROUP_SEP: ',', + PATTERNS: [ + { // Decimal Pattern + minInt: 1, + minFrac: 0, + maxFrac: 3, + posPre: '', + posSuf: '', + negPre: '-', + negSuf: '', + gSize: 3, + lgSize: 3 + },{ //Currency Pattern + minInt: 1, + minFrac: 2, + maxFrac: 2, + posPre: '\u00A4', + posSuf: '', + negPre: '(\u00A4', + negSuf: ')', + gSize: 3, + lgSize: 3 + } + ], + CURRENCY_SYM: '$' + }, + + DATETIME_FORMATS: { + MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' + .split(','), + SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), + DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), + SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), + AMPMS: ['AM','PM'], + medium: 'MMM d, y h:mm:ss a', + short: 'M/d/yy h:mm a', + fullDate: 'EEEE, MMMM d, y', + longDate: 'MMMM d, y', + mediumDate: 'MMM d, y', + shortDate: 'M/d/yy', + mediumTime: 'h:mm:ss a', + shortTime: 'h:mm a' + }, + + pluralCat: function(num) { + if (num === 1) { + return 'one'; + } + return 'other'; + } + }; + }; } +var SERVER_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/, + PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/, + DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; +var $locationMinErr = minErr('$location'); + /** - * Constructs a promise manager. + * Encode path using encodeUriSegment, ignoring forward slashes * - * @param {function(function)} nextTick Function for executing functions in the next turn. - * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for - * debugging purposes. - * @returns {object} Promise manager. + * @param {string} path Path to encode + * @returns {string} */ -function qFactory(nextTick, exceptionHandler) { +function encodePath(path) { + var segments = path.split('/'), + i = segments.length; - /** - * @ngdoc - * @name ng.$q#defer - * @methodOf ng.$q - * @description - * Creates a `Deferred` object which represents a task which will finish in the future. - * - * @returns {Deferred} Returns a new instance of deferred. - */ - var defer = function() { - var pending = [], - value, deferred; + while (i--) { + segments[i] = encodeUriSegment(segments[i]); + } - deferred = { + return segments.join('/'); +} - resolve: function(val) { - if (pending) { - var callbacks = pending; - pending = undefined; - value = ref(val); +function matchUrl(url, obj) { + var match = SERVER_MATCH.exec(url); - if (callbacks.length) { - nextTick(function() { - var callback; - for (var i = 0, ii = callbacks.length; i < ii; i++) { - callback = callbacks[i]; - value.then(callback[0], callback[1]); - } - }); - } - } - }, + obj.$$protocol = match[1]; + obj.$$host = match[3]; + obj.$$port = int(match[5]) || DEFAULT_PORTS[match[1]] || null; +} +function matchAppUrl(url, obj) { + var match = PATH_MATCH.exec(url); - reject: function(reason) { - deferred.resolve(reject(reason)); - }, + obj.$$path = decodeURIComponent(match[1]); + obj.$$search = parseKeyValue(match[3]); + obj.$$hash = decodeURIComponent(match[5] || ''); + // make sure path starts with '/'; + if (obj.$$path && obj.$$path.charAt(0) != '/') obj.$$path = '/' + obj.$$path; +} - promise: { - then: function(callback, errback) { - var result = defer(); - var wrappedCallback = function(value) { - try { - result.resolve((callback || defaultCallback)(value)); - } catch(e) { - exceptionHandler(e); - result.reject(e); - } - }; +function composeProtocolHostPort(protocol, host, port) { + return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port); +} - var wrappedErrback = function(reason) { - try { - result.resolve((errback || defaultErrback)(reason)); - } catch(e) { - exceptionHandler(e); - result.reject(e); - } - }; +/** + * + * @param {string} begin + * @param {string} whole + * @param {string} otherwise + * @returns {string} returns text from whole after begin or otherwise if it does not begin with expected string. + */ +function beginsWith(begin, whole, otherwise) { + return whole.indexOf(begin) == 0 ? whole.substr(begin.length) : otherwise; +} - if (pending) { - pending.push([wrappedCallback, wrappedErrback]); - } else { - value.then(wrappedCallback, wrappedErrback); - } - return result.promise; - } - } - }; +function stripHash(url) { + var index = url.indexOf('#'); + return index == -1 ? url : url.substr(0, index); +} - return deferred; - }; +function stripFile(url) { + return url.substr(0, stripHash(url).lastIndexOf('/') + 1); +} - var ref = function(value) { - if (value && value.then) return value; - return { - then: function(callback) { - var result = defer(); - nextTick(function() { - result.resolve(callback(value)); - }); - return result.promise; - } - }; - }; +/* return the server only (scheme://host:port) */ +function serverBase(url) { + return url.substring(0, url.indexOf('/', url.indexOf('//') + 2)); +} +/** + * LocationHtml5Url represents an url + * This object is exposed as $location service when HTML5 mode is enabled and supported + * + * @constructor + * @param {string} appBase application base URL + * @param {string} basePrefix url path prefix + */ +function LocationHtml5Url(appBase, basePrefix) { + this.$$html5 = true; + basePrefix = basePrefix || ''; + var appBaseNoFile = stripFile(appBase); /** - * @ngdoc - * @name ng.$q#reject - * @methodOf ng.$q - * @description - * Creates a promise that is resolved as rejected with the specified `reason`. This api should be - * used to forward rejection in a chain of promises. If you are dealing with the last promise in - * a promise chain, you don't need to worry about it. - * - * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of - * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via - * a promise error callback and you want to forward the error to the promise derived from the - * current promise, you have to "rethrow" the error by returning a rejection constructed via - * `reject`. - * - *
-   *   promiseB = promiseA.then(function(result) {
-   *     // success: do something and resolve promiseB
-   *     //          with the old or a new result
-   *     return result;
-   *   }, function(reason) {
-   *     // error: handle the error if possible and
-   *     //        resolve promiseB with newPromiseOrValue,
-   *     //        otherwise forward the rejection to promiseB
-   *     if (canHandle(reason)) {
-   *      // handle the error and recover
-   *      return newPromiseOrValue;
-   *     }
-   *     return $q.reject(reason);
-   *   });
-   * 
- * - * @param {*} reason Constant, message, exception or an object representing the rejection reason. - * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. + * Parse given html5 (regular) url string into properties + * @param {string} newAbsoluteUrl HTML5 url + * @private */ - var reject = function(reason) { - return { - then: function(callback, errback) { - var result = defer(); - nextTick(function() { - result.resolve((errback || defaultErrback)(reason)); - }); - return result.promise; - } - }; - }; + this.$$parse = function(url) { + var parsed = {} + matchUrl(url, parsed); + var pathUrl = beginsWith(appBaseNoFile, url); + if (!isString(pathUrl)) { + throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url, appBaseNoFile); + } + matchAppUrl(pathUrl, parsed); + extend(this, parsed); + if (!this.$$path) { + this.$$path = '/'; + } + this.$$compose(); + }; /** - * @ngdoc - * @name ng.$q#when - * @methodOf ng.$q - * @description - * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. - * This is useful when you are dealing with an object that might or might not be a promise, or if - * the promise comes from a source that can't be trusted. - * - * @param {*} value Value or a promise - * @returns {Promise} Returns a promise of the passed value or promise + * Compose url and update `absUrl` property + * @private */ - var when = function(value, callback, errback) { - var result = defer(), - done; - - var wrappedCallback = function(value) { - try { - return (callback || defaultCallback)(value); - } catch (e) { - exceptionHandler(e); - return reject(e); - } - }; - - var wrappedErrback = function(reason) { - try { - return (errback || defaultErrback)(reason); - } catch (e) { - exceptionHandler(e); - return reject(e); - } - }; - - nextTick(function() { - ref(value).then(function(value) { - if (done) return; - done = true; - result.resolve(ref(value).then(wrappedCallback, wrappedErrback)); - }, function(reason) { - if (done) return; - done = true; - result.resolve(wrappedErrback(reason)); - }); - }); + this.$$compose = function() { + var search = toKeyValue(this.$$search), + hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; - return result.promise; + this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; + this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/' }; + this.$$rewrite = function(url) { + var appUrl, prevAppUrl; - function defaultCallback(value) { - return value; + if ( (appUrl = beginsWith(appBase, url)) !== undefined ) { + prevAppUrl = appUrl; + if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) { + return appBaseNoFile + (beginsWith('/', appUrl) || appUrl); + } else { + return appBase + prevAppUrl; + } + } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) { + return appBaseNoFile + appUrl; + } else if (appBaseNoFile == url + '/') { + return appBaseNoFile; + } } +} - function defaultErrback(reason) { - return reject(reason); - } +/** + * LocationHashbangUrl represents url + * This object is exposed as $location service when developer doesn't opt into html5 mode. + * It also serves as the base class for html5 mode fallback on legacy browsers. + * + * @constructor + * @param {string} appBase application base URL + * @param {string} hashPrefix hashbang prefix + */ +function LocationHashbangUrl(appBase, hashPrefix) { + var appBaseNoFile = stripFile(appBase); + + matchUrl(appBase, this); /** - * @ngdoc - * @name ng.$q#all - * @methodOf ng.$q - * @description - * Combines multiple promises into a single promise that is resolved when all of the input - * promises are resolved. - * - * @param {Array.} promises An array of promises. - * @returns {Promise} Returns a single promise that will be resolved with an array of values, - * each value corresponding to the promise at the same index in the `promises` array. If any of - * the promises is resolved with a rejection, this resulting promise will be resolved with the - * same rejection. + * Parse given hashbang url into properties + * @param {string} url Hashbang url + * @private */ - function all(promises) { - var deferred = defer(), - counter = promises.length, - results = []; - - if (counter) { - forEach(promises, function(promise, index) { - ref(promise).then(function(value) { - if (index in results) return; - results[index] = value; - if (!(--counter)) deferred.resolve(results); - }, function(reason) { - if (index in results) return; - deferred.reject(reason); - }); - }); - } else { - deferred.resolve(results); + this.$$parse = function(url) { + var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url); + var withoutHashUrl = withoutBaseUrl.charAt(0) == '#' + ? beginsWith(hashPrefix, withoutBaseUrl) + : (this.$$html5) + ? withoutBaseUrl + : ''; + + if (!isString(withoutHashUrl)) { + throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url, hashPrefix); } + matchAppUrl(withoutHashUrl, this); + this.$$compose(); + }; - return deferred.promise; - } + /** + * Compose hashbang url and update `absUrl` property + * @private + */ + this.$$compose = function() { + var search = toKeyValue(this.$$search), + hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; - return { - defer: defer, - reject: reject, - when: when, - all: all + this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; + this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : ''); }; + + this.$$rewrite = function(url) { + if(stripHash(appBase) == stripHash(url)) { + return url; + } + } } + /** - * @ngdoc object - * @name ng.$routeProvider - * @function - * - * @description + * LocationHashbangUrl represents url + * This object is exposed as $location service when html5 history api is enabled but the browser + * does not support it. * - * Used for configuring routes. See {@link ng.$route $route} for an example. + * @constructor + * @param {string} appBase application base URL + * @param {string} hashPrefix hashbang prefix */ -function $RouteProvider(){ - var routes = {}; +function LocationHashbangInHtml5Url(appBase, hashPrefix) { + this.$$html5 = true; + LocationHashbangUrl.apply(this, arguments); + + var appBaseNoFile = stripFile(appBase); + + this.$$rewrite = function(url) { + var appUrl; + + if ( appBase == stripHash(url) ) { + return url; + } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) { + return appBase + hashPrefix + appUrl; + } else if ( appBaseNoFile === url + '/') { + return appBaseNoFile; + } + } +} + + +LocationHashbangInHtml5Url.prototype = + LocationHashbangUrl.prototype = + LocationHtml5Url.prototype = { + + /** + * Are we in html5 mode? + * @private + */ + $$html5: false, + + /** + * Has any change been replacing ? + * @private + */ + $$replace: false, + + /** + * @ngdoc method + * @name ng.$location#absUrl + * @methodOf ng.$location + * + * @description + * This method is getter only. + * + * Return full url representation with all segments encoded according to rules specified in + * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}. + * + * @return {string} full url + */ + absUrl: locationGetter('$$absUrl'), + + /** + * @ngdoc method + * @name ng.$location#url + * @methodOf ng.$location + * + * @description + * This method is getter / setter. + * + * Return url (e.g. `/path?a=b#hash`) when called without any parameter. + * + * Change path, search and hash, when called with parameter and return `$location`. + * + * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) + * @param {string=} replace The path that will be changed + * @return {string} url + */ + url: function(url, replace) { + if (isUndefined(url)) + return this.$$url; + + var match = PATH_MATCH.exec(url); + if (match[1]) this.path(decodeURIComponent(match[1])); + if (match[2] || match[1]) this.search(match[3] || ''); + this.hash(match[5] || '', replace); + + return this; + }, /** * @ngdoc method - * @name ng.$routeProvider#when - * @methodOf ng.$routeProvider + * @name ng.$location#protocol + * @methodOf ng.$location * - * @param {string} path Route path (matched against `$location.path`). If `$location.path` - * contains redundant trailing slash or is missing one, the route will still match and the - * `$location.path` will be updated to add or drop the trailing slash to exactly match the - * route definition. + * @description + * This method is getter only. * - * `path` can contain named groups starting with a colon (`:name`). All characters up to the - * next slash are matched and stored in `$routeParams` under the given `name` when the route - * matches. + * Return protocol of current url. * - * @param {Object} route Mapping information to be assigned to `$route.current` on route - * match. + * @return {string} protocol of current url + */ + protocol: locationGetter('$$protocol'), + + /** + * @ngdoc method + * @name ng.$location#host + * @methodOf ng.$location * - * Object properties: + * @description + * This method is getter only. * - * - `controller` – `{(string|function()=}` – Controller fn that should be associated with newly - * created scope or the name of a {@link angular.Module#controller registered controller} - * if passed as a string. - * - `template` – `{string=}` – html template as a string that should be used by - * {@link ng.directive:ngView ngView} or - * {@link ng.directive:ngInclude ngInclude} directives. - * this property takes precedence over `templateUrl`. - * - `templateUrl` – `{string=}` – path to an html template that should be used by - * {@link ng.directive:ngView ngView}. - * - `resolve` - `{Object.=}` - An optional map of dependencies which should - * be injected into the controller. If any of these dependencies are promises, they will be - * resolved and converted to a value before the controller is instantiated and the - * `$routeChangeSuccess` event is fired. The map object is: + * Return host of current url. * - * - `key` – `{string}`: a name of a dependency to be injected into the controller. - * - `factory` - `{string|function}`: If `string` then it is an alias for a service. - * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected} - * and the return value is treated as the dependency. If the result is a promise, it is resolved - * before its value is injected into the controller. + * @return {string} host of current url. + */ + host: locationGetter('$$host'), + + /** + * @ngdoc method + * @name ng.$location#port + * @methodOf ng.$location * - * - `redirectTo` – {(string|function())=} – value to update - * {@link ng.$location $location} path with and trigger route redirection. + * @description + * This method is getter only. * - * If `redirectTo` is a function, it will be called with the following parameters: + * Return port of current url. * - * - `{Object.}` - route parameters extracted from the current - * `$location.path()` by applying the current route templateUrl. - * - `{string}` - current `$location.path()` - * - `{Object}` - current `$location.search()` + * @return {Number} port + */ + port: locationGetter('$$port'), + + /** + * @ngdoc method + * @name ng.$location#path + * @methodOf ng.$location * - * The custom `redirectTo` function is expected to return a string which will be used - * to update `$location.path()` and `$location.search()`. + * @description + * This method is getter / setter. * - * - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search() - * changes. + * Return path of current url when called without any parameter. * - * If the option is set to `false` and url in the browser changes, then - * `$routeUpdate` event is broadcasted on the root scope. + * Change path when called with parameter and return `$location`. * - * @returns {Object} self + * Note: Path should always begin with forward slash (/), this method will add the forward slash + * if it is missing. * - * @description - * Adds a new route definition to the `$route` service. + * @param {string=} path New path + * @return {string} path */ - this.when = function(path, route) { - routes[path] = extend({reloadOnSearch: true}, route); - - // create redirection for trailing slashes - if (path) { - var redirectPath = (path[path.length-1] == '/') - ? path.substr(0, path.length-1) - : path +'/'; + path: locationGetterSetter('$$path', function(path) { + return path.charAt(0) == '/' ? path : '/' + path; + }), - routes[redirectPath] = {redirectTo: path}; + /** + * @ngdoc method + * @name ng.$location#search + * @methodOf ng.$location + * + * @description + * This method is getter / setter. + * + * Return search part (as object) of current url when called without any parameter. + * + * Change search part when called with parameter and return `$location`. + * + * @param {string|Object.|Object.>} search New search params - string or hash object. Hash object + * may contain an array of values, which will be decoded as duplicates in the url. + * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a + * single search parameter. If the value is `null`, the parameter will be deleted. + * + * @return {string} search + */ + search: function(search, paramValue) { + switch (arguments.length) { + case 0: + return this.$$search; + case 1: + if (isString(search)) { + this.$$search = parseKeyValue(search); + } else if (isObject(search)) { + this.$$search = search; + } else { + throw $locationMinErr('isrcharg', 'The first argument of the `$location#search()` call must be a string or an object.'); + } + break; + default: + if (paramValue == undefined || paramValue == null) { + delete this.$$search[search]; + } else { + this.$$search[search] = paramValue; + } } + this.$$compose(); return this; - }; + }, /** * @ngdoc method - * @name ng.$routeProvider#otherwise - * @methodOf ng.$routeProvider + * @name ng.$location#hash + * @methodOf ng.$location * * @description - * Sets route definition that will be used on route change when no other route definition - * is matched. + * This method is getter / setter. + * + * Return hash fragment when called without any parameter. + * + * Change hash fragment when called with parameter and return `$location`. + * + * @param {string=} hash New hash fragment + * @return {string} hash + */ + hash: locationGetterSetter('$$hash', identity), + + /** + * @ngdoc method + * @name ng.$location#replace + * @methodOf ng.$location * - * @param {Object} params Mapping information to be assigned to `$route.current`. - * @returns {Object} self + * @description + * If called, all changes to $location during current `$digest` will be replacing current history + * record, instead of adding new one. */ - this.otherwise = function(params) { - this.when(null, params); + replace: function() { + this.$$replace = true; return this; + } +}; + +function locationGetter(property) { + return function() { + return this[property]; }; +} - this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache', - function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) { +function locationGetterSetter(property, preprocess) { + return function(value) { + if (isUndefined(value)) + return this[property]; - /** - * @ngdoc object - * @name ng.$route - * @requires $location - * @requires $routeParams - * - * @property {Object} current Reference to the current route definition. - * The route definition contains: - * - * - `controller`: The controller constructor as define in route definition. - * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for - * controller instantiation. The `locals` contain - * the resolved values of the `resolve` map. Additionally the `locals` also contain: - * - * - `$scope` - The current route scope. - * - `$template` - The current route template HTML. - * - * @property {Array.} routes Array of all configured routes. - * - * @description - * Is used for deep-linking URLs to controllers and views (HTML partials). - * It watches `$location.url()` and tries to map the path to an existing route definition. - * - * You can define routes through {@link ng.$routeProvider $routeProvider}'s API. - * - * The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView} - * directive and the {@link ng.$routeParams $routeParams} service. - * - * @example - This example shows how changing the URL hash causes the `$route` to match a route against the - URL, and the `ngView` pulls in the partial. - - Note that this example is using {@link ng.directive:script inlined templates} - to get it working on jsfiddle as well. - - - -
- Choose: - Moby | - Moby: Ch1 | - Gatsby | - Gatsby: Ch4 | - Scarlet Letter
- -
-
- -
$location.path() = {{$location.path()}}
-
$route.current.templateUrl = {{$route.current.templateUrl}}
-
$route.current.params = {{$route.current.params}}
-
$route.current.scope.name = {{$route.current.scope.name}}
-
$routeParams = {{$routeParams}}
-
-
- - - controller: {{name}}
- Book Id: {{params.bookId}}
-
- - - controller: {{name}}
- Book Id: {{params.bookId}}
- Chapter Id: {{params.chapterId}} -
- - - angular.module('ngView', [], function($routeProvider, $locationProvider) { - $routeProvider.when('/Book/:bookId', { - templateUrl: 'book.html', - controller: BookCntl, - resolve: { - // I will cause a 1 second delay - delay: function($q, $timeout) { - var delay = $q.defer(); - $timeout(delay.resolve, 1000); - return delay.promise; - } - } - }); - $routeProvider.when('/Book/:bookId/ch/:chapterId', { - templateUrl: 'chapter.html', - controller: ChapterCntl - }); + this[property] = preprocess(value); + this.$$compose(); - // configure html5 to get links working on jsfiddle - $locationProvider.html5Mode(true); - }); + return this; + }; +} - function MainCntl($scope, $route, $routeParams, $location) { - $scope.$route = $route; - $scope.$location = $location; - $scope.$routeParams = $routeParams; - } - function BookCntl($scope, $routeParams) { - $scope.name = "BookCntl"; - $scope.params = $routeParams; - } +/** + * @ngdoc object + * @name ng.$location + * + * @requires $browser + * @requires $sniffer + * @requires $rootElement + * + * @description + * The $location service parses the URL in the browser address bar (based on the + * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL + * available to your application. Changes to the URL in the address bar are reflected into + * $location service and changes to $location are reflected into the browser address bar. + * + * **The $location service:** + * + * - Exposes the current URL in the browser address bar, so you can + * - Watch and observe the URL. + * - Change the URL. + * - Synchronizes the URL with the browser when the user + * - Changes the address bar. + * - Clicks the back or forward button (or clicks a History link). + * - Clicks on a link. + * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). + * + * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular + * Services: Using $location} + */ - function ChapterCntl($scope, $routeParams) { - $scope.name = "ChapterCntl"; - $scope.params = $routeParams; - } - - - - it('should load and compile correct template', function() { - element('a:contains("Moby: Ch1")').click(); - var content = element('.doc-example-live [ng-view]').text(); - expect(content).toMatch(/controller\: ChapterCntl/); - expect(content).toMatch(/Book Id\: Moby/); - expect(content).toMatch(/Chapter Id\: 1/); - - element('a:contains("Scarlet")').click(); - sleep(2); // promises are not part of scenario waiting - content = element('.doc-example-live [ng-view]').text(); - expect(content).toMatch(/controller\: BookCntl/); - expect(content).toMatch(/Book Id\: Scarlet/); - }); - -
- */ +/** + * @ngdoc object + * @name ng.$locationProvider + * @description + * Use the `$locationProvider` to configure how the application deep linking paths are stored. + */ +function $LocationProvider(){ + var hashPrefix = '', + html5Mode = false; - /** - * @ngdoc event - * @name ng.$route#$routeChangeStart - * @eventOf ng.$route - * @eventType broadcast on root scope - * @description - * Broadcasted before a route change. At this point the route services starts - * resolving all of the dependencies needed for the route change to occurs. - * Typically this involves fetching the view template as well as any dependencies - * defined in `resolve` route property. Once all of the dependencies are resolved - * `$routeChangeSuccess` is fired. - * - * @param {Route} next Future route information. - * @param {Route} current Current route information. - */ + /** + * @ngdoc property + * @name ng.$locationProvider#hashPrefix + * @methodOf ng.$locationProvider + * @description + * @param {string=} prefix Prefix for hash part (containing path and search) + * @returns {*} current value if used as getter or itself (chaining) if used as setter + */ + this.hashPrefix = function(prefix) { + if (isDefined(prefix)) { + hashPrefix = prefix; + return this; + } else { + return hashPrefix; + } + }; - /** - * @ngdoc event - * @name ng.$route#$routeChangeSuccess - * @eventOf ng.$route - * @eventType broadcast on root scope - * @description - * Broadcasted after a route dependencies are resolved. - * {@link ng.directive:ngView ngView} listens for the directive - * to instantiate the controller and render the view. - * - * @param {Object} angularEvent Synthetic event object. - * @param {Route} current Current route information. - * @param {Route|Undefined} previous Previous route information, or undefined if current is first route entered. - */ + /** + * @ngdoc property + * @name ng.$locationProvider#html5Mode + * @methodOf ng.$locationProvider + * @description + * @param {string=} mode Use HTML5 strategy if available. + * @returns {*} current value if used as getter or itself (chaining) if used as setter + */ + this.html5Mode = function(mode) { + if (isDefined(mode)) { + html5Mode = mode; + return this; + } else { + return html5Mode; + } + }; - /** - * @ngdoc event - * @name ng.$route#$routeChangeError - * @eventOf ng.$route - * @eventType broadcast on root scope - * @description - * Broadcasted if any of the resolve promises are rejected. - * - * @param {Route} current Current route information. - * @param {Route} previous Previous route information. - * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. - */ + this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', + function( $rootScope, $browser, $sniffer, $rootElement) { + var $location, + LocationMode, + baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to '' + initialUrl = $browser.url(), + appBase; - /** - * @ngdoc event - * @name ng.$route#$routeUpdate - * @eventOf ng.$route - * @eventType broadcast on root scope - * @description - * - * The `reloadOnSearch` property has been set to false, and we are reusing the same - * instance of the Controller. - */ + if (html5Mode) { + appBase = serverBase(initialUrl) + (baseHref || '/'); + LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; + } else { + appBase = stripHash(initialUrl); + LocationMode = LocationHashbangUrl; + } + $location = new LocationMode(appBase, '#' + hashPrefix); + $location.$$parse($location.$$rewrite(initialUrl)); - var forceReload = false, - $route = { - routes: routes, + $rootElement.on('click', function(event) { + // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) + // currently we open nice url link and redirect then - /** - * @ngdoc method - * @name ng.$route#reload - * @methodOf ng.$route - * - * @description - * Causes `$route` service to reload the current route even if - * {@link ng.$location $location} hasn't changed. - * - * As a result of that, {@link ng.directive:ngView ngView} - * creates new scope, reinstantiates the controller. - */ - reload: function() { - forceReload = true; - $rootScope.$evalAsync(updateRoute); - } - }; + if (event.ctrlKey || event.metaKey || event.which == 2) return; + + var elm = jqLite(event.target); + + // traverse the DOM up to find first A tag + while (lowercase(elm[0].nodeName) !== 'a') { + // ignore rewriting if no A tag (reached root element, or no parent - removed from document) + if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; + } + + var absHref = elm.prop('href'); + var rewrittenUrl = $location.$$rewrite(absHref); + + if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) { + event.preventDefault(); + if (rewrittenUrl != $browser.url()) { + // update location manually + $location.$$parse(rewrittenUrl); + $rootScope.$apply(); + // hack to work around FF6 bug 684208 when scenario runner clicks on links + window.angular['ff-684208-preventDefault'] = true; + } + } + }); - $rootScope.$on('$locationChangeSuccess', updateRoute); - return $route; + // rewrite hashbang url <> html5 url + if ($location.absUrl() != initialUrl) { + $browser.url($location.absUrl(), true); + } - ///////////////////////////////////////////////////// + // update $location when $browser url changes + $browser.onUrlChange(function(newUrl) { + if ($location.absUrl() != newUrl) { + if ($rootScope.$broadcast('$locationChangeStart', newUrl, $location.absUrl()).defaultPrevented) { + $browser.url($location.absUrl()); + return; + } + $rootScope.$evalAsync(function() { + var oldUrl = $location.absUrl(); - /** - * @param on {string} current url - * @param when {string} route when template to match the url against - * @return {?Object} - */ - function switchRouteMatcher(on, when) { - // TODO(i): this code is convoluted and inefficient, we should construct the route matching - // regex only once and then reuse it - - // Escape regexp special characters. - when = '^' + when.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&") + '$'; - var regex = '', - params = [], - dst = {}; - - var re = /:(\w+)/g, - paramMatch, - lastMatchedIndex = 0; - - while ((paramMatch = re.exec(when)) !== null) { - // Find each :param in `when` and replace it with a capturing group. - // Append all other sections of when unchanged. - regex += when.slice(lastMatchedIndex, paramMatch.index); - regex += '([^\\/]*)'; - params.push(paramMatch[1]); - lastMatchedIndex = re.lastIndex; - } - // Append trailing path part. - regex += when.substr(lastMatchedIndex); - - var match = on.match(new RegExp(regex)); - if (match) { - forEach(params, function(name, index) { - dst[name] = match[index + 1]; + $location.$$parse(newUrl); + afterLocationChange(oldUrl); }); + if (!$rootScope.$$phase) $rootScope.$digest(); } - return match ? dst : null; - } - - function updateRoute() { - var next = parseRoute(), - last = $route.current; - - if (next && last && next.$$route === last.$$route - && equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { - last.params = next.params; - copy(last.params, $routeParams); - $rootScope.$broadcast('$routeUpdate', last); - } else if (next || last) { - forceReload = false; - $rootScope.$broadcast('$routeChangeStart', next, last); - $route.current = next; - if (next) { - if (next.redirectTo) { - if (isString(next.redirectTo)) { - $location.path(interpolate(next.redirectTo, next.params)).search(next.params) - .replace(); - } else { - $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) - .replace(); - } - } - } + }); - $q.when(next). - then(function() { - if (next) { - var keys = [], - values = [], - template; + // update browser + var changeCounter = 0; + $rootScope.$watch(function $locationWatch() { + var oldUrl = $browser.url(); + var currentReplace = $location.$$replace; - forEach(next.resolve || {}, function(value, key) { - keys.push(key); - values.push(isString(value) ? $injector.get(value) : $injector.invoke(value)); - }); - if (isDefined(template = next.template)) { - } else if (isDefined(template = next.templateUrl)) { - template = $http.get(template, {cache: $templateCache}). - then(function(response) { return response.data; }); - } - if (isDefined(template)) { - keys.push('$template'); - values.push(template); - } - return $q.all(values).then(function(values) { - var locals = {}; - forEach(values, function(value, index) { - locals[keys[index]] = value; - }); - return locals; - }); - } - }). - // after route change - then(function(locals) { - if (next == $route.current) { - if (next) { - next.locals = locals; - copy(next.params, $routeParams); - } - $rootScope.$broadcast('$routeChangeSuccess', next, last); - } - }, function(error) { - if (next == $route.current) { - $rootScope.$broadcast('$routeChangeError', next, last, error); - } - }); + if (!changeCounter || oldUrl != $location.absUrl()) { + changeCounter++; + $rootScope.$evalAsync(function() { + if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl). + defaultPrevented) { + $location.$$parse(oldUrl); + } else { + $browser.url($location.absUrl(), currentReplace); + afterLocationChange(oldUrl); + } + }); } - } + $location.$$replace = false; + return changeCounter; + }); - /** - * @returns the current active route, by matching it against the URL - */ - function parseRoute() { - // Match a route - var params, match; - forEach(routes, function(route, path) { - if (!match && (params = switchRouteMatcher($location.path(), path))) { - match = inherit(route, { - params: extend({}, $location.search(), params), - pathParams: params}); - match.$$route = route; - } - }); - // No route matched; fallback to "otherwise" route - return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); - } + return $location; - /** - * @returns interpolation of the redirect path with the parametrs - */ - function interpolate(string, params) { - var result = []; - forEach((string||'').split(':'), function(segment, i) { - if (i == 0) { - result.push(segment); - } else { - var segmentMatch = segment.match(/(\w+)(.*)/); - var key = segmentMatch[1]; - result.push(params[key]); - result.push(segmentMatch[2] || ''); - delete params[key]; - } - }); - return result.join(''); + function afterLocationChange(oldUrl) { + $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl); } - }]; +}]; } /** * @ngdoc object - * @name ng.$routeParams - * @requires $route + * @name ng.$log + * @requires $window * * @description - * Current set of route parameters. The route parameters are a combination of the - * {@link ng.$location $location} `search()`, and `path()`. The `path` parameters - * are extracted when the {@link ng.$route $route} path is matched. - * - * In case of parameter name collision, `path` params take precedence over `search` params. + * Simple service for logging. Default implementation writes the message + * into the browser's console (if present). * - * The service guarantees that the identity of the `$routeParams` object will remain unchanged - * (but its properties will likely change) even when a route change occurs. + * The main purpose of this service is to simplify debugging and troubleshooting. * * @example - *
- *  // Given:
- *  // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
- *  // Route: /Chapter/:chapterId/Section/:sectionId
- *  //
- *  // Then
- *  $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
- * 
- */ -function $RouteParamsProvider() { - this.$get = valueFn({}); -} - -/** - * DESIGN NOTES - * - * The design decisions behind the scope are heavily favored for speed and memory consumption. - * - * The typical use of scope is to watch the expressions, which most of the time return the same - * value as last time so we optimize the operation. - * - * Closures construction is expensive in terms of speed as well as memory: - * - No closures, instead use prototypical inheritance for API - * - Internal state needs to be stored on scope directly, which means that private state is - * exposed as $$____ properties - * - * Loop operations are optimized by using while(count--) { ... } - * - this means that in order to keep the same order of execution as addition we have to add - * items to the array at the beginning (shift) instead of at the end (push) - * - * Child scopes are created and removed often - * - Using an array would be slow since inserts in middle are expensive so we use linked list - * - * There are few watches then a lot of observers. This is why you don't want the observer to be - * implemented in the same way as watch. Watch requires return of initialization function which - * are expensive to construct. + + + function LogCtrl($scope, $log) { + $scope.$log = $log; + $scope.message = 'Hello World!'; + } + + +
+

Reload this page with open console, enter text and hit the log button...

+ Message: + + + + + +
+
+
*/ - /** * @ngdoc object - * @name ng.$rootScopeProvider + * @name ng.$logProvider * @description - * - * Provider for the $rootScope service. + * Use the `$logProvider` to configure how the application logs messages */ +function $LogProvider(){ + var debug = true, + self = this; + + /** + * @ngdoc property + * @name ng.$logProvider#debugEnabled + * @methodOf ng.$logProvider + * @description + * @param {string=} flag enable or disable debug level messages + * @returns {*} current value if used as getter or itself (chaining) if used as setter + */ + this.debugEnabled = function(flag) { + if (isDefined(flag)) { + debug = flag; + return this; + } else { + return debug; + } + }; + + this.$get = ['$window', function($window){ + return { + /** + * @ngdoc method + * @name ng.$log#log + * @methodOf ng.$log + * + * @description + * Write a log message + */ + log: consoleLog('log'), -/** - * @ngdoc function - * @name ng.$rootScopeProvider#digestTtl - * @methodOf ng.$rootScopeProvider - * @description - * - * Sets the number of digest iterations the scope should attempt to execute before giving up and - * assuming that the model is unstable. - * - * The current default is 10 iterations. - * - * @param {number} limit The number of digest iterations. - */ + /** + * @ngdoc method + * @name ng.$log#info + * @methodOf ng.$log + * + * @description + * Write an information message + */ + info: consoleLog('info'), + /** + * @ngdoc method + * @name ng.$log#warn + * @methodOf ng.$log + * + * @description + * Write a warning message + */ + warn: consoleLog('warn'), -/** - * @ngdoc object - * @name ng.$rootScope - * @description - * - * Every application has a single root {@link ng.$rootScope.Scope scope}. - * All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide - * event processing life-cycle. See {@link guide/scope developer guide on scopes}. - */ -function $RootScopeProvider(){ - var TTL = 10; + /** + * @ngdoc method + * @name ng.$log#error + * @methodOf ng.$log + * + * @description + * Write an error message + */ + error: consoleLog('error'), + + /** + * @ngdoc method + * @name ng.$log#debug + * @methodOf ng.$log + * + * @description + * Write a debug message + */ + debug: (function () { + var fn = consoleLog('debug'); + + return function() { + if (debug) { + fn.apply(self, arguments); + } + } + }()) + }; - this.digestTtl = function(value) { - if (arguments.length) { - TTL = value; + function formatError(arg) { + if (arg instanceof Error) { + if (arg.stack) { + arg = (arg.message && arg.stack.indexOf(arg.message) === -1) + ? 'Error: ' + arg.message + '\n' + arg.stack + : arg.stack; + } else if (arg.sourceURL) { + arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; + } + } + return arg; } - return TTL; - }; - this.$get = ['$injector', '$exceptionHandler', '$parse', - function( $injector, $exceptionHandler, $parse) { + function consoleLog(type) { + var console = $window.console || {}, + logFn = console[type] || console.log || noop; - /** - * @ngdoc function - * @name ng.$rootScope.Scope - * - * @description - * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the - * {@link AUTO.$injector $injector}. Child scopes are created using the - * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when - * compiled HTML template is executed.) - * - * Here is a simple scope snippet to show how you can interact with the scope. - *
-        angular.injector(['ng']).invoke(function($rootScope) {
-           var scope = $rootScope.$new();
-           scope.salutation = 'Hello';
-           scope.name = 'World';
+      if (logFn.apply) {
+        return function() {
+          var args = [];
+          forEach(arguments, function(arg) {
+            args.push(formatError(arg));
+          });
+          return logFn.apply(console, args);
+        };
+      }
+
+      // we are IE which either doesn't have window.console => this is noop and we do nothing,
+      // or we are IE where console.log doesn't have apply so we log at least first 2 args
+      return function(arg1, arg2) {
+        logFn(arg1, arg2);
+      }
+    }
+  }];
+}
+
+var $parseMinErr = minErr('$parse');
+
+// Sandboxing Angular Expressions
+// ------------------------------
+// Angular expressions are generally considered safe because these expressions only have direct access to $scope and
+// locals. However, one can obtain the ability to execute arbitrary JS code by obtaining a reference to native JS
+// functions such as the Function constructor.
+//
+// As an example, consider the following Angular expression:
+//
+//   {}.toString.constructor(alert("evil JS code"))
+//
+// We want to prevent this type of access. For the sake of performance, during the lexing phase we disallow any "dotted"
+// access to any member named "constructor".
+//
+// For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor while evaluating
+// For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor while evaluating
+// the expression, which is a stronger but more expensive test. Since reflective calls are expensive anyway, this is not
+// such a big deal compared to static dereferencing.
+//
+// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits against the
+// expression language, but not to prevent exploits that were enabled by exposing sensitive JavaScript or browser apis
+// on Scope. Exposing such objects on a Scope is never a good practice and therefore we are not even trying to protect
+// against interaction with an object explicitly exposed in this way.
+//
+// A developer could foil the name check by aliasing the Function constructor under a different name on the scope.
+//
+// In general, it is not possible to access a Window object from an angular expression unless a window or some DOM
+// object that has a reference to window is published onto a Scope.
 
-           expect(scope.greeting).toEqual(undefined);
+function ensureSafeMemberName(name, fullExpression) {
+  if (name === "constructor") {
+    throw $parseMinErr('isecfld',
+        'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}', fullExpression);
+  }
+  return name;
+};
 
-           scope.$watch('name', function() {
-             scope.greeting = scope.salutation + ' ' + scope.name + '!';
-           }); // initialize the watch
+function ensureSafeObject(obj, fullExpression) {
+  // nifty check if obj is Function that is fast and works across iframes and other contexts
+  if (obj && obj.constructor === obj) {
+    throw $parseMinErr('isecfn',
+        'Referencing Function in Angular expressions is disallowed! Expression: {0}', fullExpression);
+  } else {
+    return obj;
+  }
+}
 
-           expect(scope.greeting).toEqual(undefined);
-           scope.name = 'Misko';
-           // still old value, since watches have not been called yet
-           expect(scope.greeting).toEqual(undefined);
 
-           scope.$digest(); // fire all  the watches
-           expect(scope.greeting).toEqual('Hello Misko!');
-        });
-     * 
- * - * # Inheritance - * A scope can inherit from a parent scope, as in this example: - *
-         var parent = $rootScope;
-         var child = parent.$new();
+var OPERATORS = {
+    'null':function(){return null;},
+    'true':function(){return true;},
+    'false':function(){return false;},
+    undefined:noop,
+    '+':function(self, locals, a,b){
+      a=a(self, locals); b=b(self, locals);
+      if (isDefined(a)) {
+        if (isDefined(b)) {
+          return a + b;
+        }
+        return a;
+      }
+      return isDefined(b)?b:undefined;},
+    '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);},
+    '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
+    '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
+    '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
+    '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
+    '=':noop,
+    '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
+    '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
+    '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
+    '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
+    '<':function(self, locals, a,b){return a(self, locals)':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
+    '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
+    '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
+    '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
+    '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
+    '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
+//    '|':function(self, locals, a,b){return a|b;},
+    '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
+    '!':function(self, locals, a){return !a(self, locals);}
+};
+var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
 
-         parent.salutation = "Hello";
-         child.name = "World";
-         expect(child.salutation).toEqual('Hello');
+function lex(text, csp){
+  var tokens = [],
+      token,
+      index = 0,
+      json = [],
+      ch,
+      lastCh = ':'; // can start regexp
 
-         child.salutation = "Welcome";
-         expect(child.salutation).toEqual('Welcome');
-         expect(parent.salutation).toEqual('Hello');
-     * 
- * - * - * @param {Object.=} providers Map of service factory which need to be provided - * for the current scope. Defaults to {@link ng}. - * @param {Object.=} instanceCache Provides pre-instantiated services which should - * append/override services provided by `providers`. This is handy when unit-testing and having - * the need to override a default service. - * @returns {Object} Newly created scope. - * - */ - function Scope() { - this.$id = nextUid(); - this.$$phase = this.$parent = this.$$watchers = - this.$$nextSibling = this.$$prevSibling = - this.$$childHead = this.$$childTail = null; - this['this'] = this.$root = this; - this.$$destroyed = false; - this.$$asyncQueue = []; - this.$$listeners = {}; - this.$$isolateBindings = {}; + while (index < text.length) { + ch = text.charAt(index); + if (is('"\'')) { + readString(ch); + } else if (isNumber(ch) || is('.') && isNumber(peek())) { + readNumber(); + } else if (isIdent(ch)) { + readIdent(); + // identifiers can only be if the preceding char was a { or , + if (was('{,') && json[0]=='{' && + (token=tokens[tokens.length-1])) { + token.json = token.text.indexOf('.') == -1; + } + } else if (is('(){}[].,;:?')) { + tokens.push({ + index:index, + text:ch, + json:(was(':[,') && is('{[')) || is('}]:,') + }); + if (is('{[')) json.unshift(ch); + if (is('}]')) json.shift(); + index++; + } else if (isWhitespace(ch)) { + index++; + continue; + } else { + var ch2 = ch + peek(), + ch3 = ch2 + peek(2), + fn = OPERATORS[ch], + fn2 = OPERATORS[ch2], + fn3 = OPERATORS[ch3]; + if (fn3) { + tokens.push({index:index, text:ch3, fn:fn3}); + index += 3; + } else if (fn2) { + tokens.push({index:index, text:ch2, fn:fn2}); + index += 2; + } else if (fn) { + tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); + index += 1; + } else { + throwError("Unexpected next character ", index, index+1); + } } + lastCh = ch; + } + return tokens; - /** - * @ngdoc property - * @name ng.$rootScope.Scope#$id - * @propertyOf ng.$rootScope.Scope - * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for - * debugging. - */ + function is(chars) { + return chars.indexOf(ch) != -1; + } + function was(chars) { + return chars.indexOf(lastCh) != -1; + } - Scope.prototype = { - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$new - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Creates a new child {@link ng.$rootScope.Scope scope}. - * - * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and - * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope - * hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. - * - * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for - * the scope and its child scopes to be permanently detached from the parent and thus stop - * participating in model change detection and listener notification by invoking. - * - * @param {boolean} isolate if true then the scope does not prototypically inherit from the - * parent scope. The scope is isolated, as it can not see parent scope properties. - * When creating widgets it is useful for the widget to not accidentally read parent - * state. - * - * @returns {Object} The newly created child scope. - * - */ - $new: function(isolate) { - var Child, - child; + function peek(i) { + var num = i || 1; + return index + num < text.length ? text.charAt(index + num) : false; + } + function isNumber(ch) { + return '0' <= ch && ch <= '9'; + } + function isWhitespace(ch) { + return ch == ' ' || ch == '\r' || ch == '\t' || + ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 + } + function isIdent(ch) { + return 'a' <= ch && ch <= 'z' || + 'A' <= ch && ch <= 'Z' || + '_' == ch || ch == '$'; + } + function isExpOperator(ch) { + return ch == '-' || ch == '+' || isNumber(ch); + } - if (isFunction(isolate)) { - // TODO: remove at some point - throw Error('API-CHANGE: Use $controller to instantiate controllers.'); - } - if (isolate) { - child = new Scope(); - child.$root = this.$root; + function throwError(error, start, end) { + end = end || index; + var colStr = (isDefined(start) ? + "s " + start + "-" + index + " [" + text.substring(start, end) + "]" + : " " + end); + throw $parseMinErr('lexerr', "Lexer Error: {0} at column{1} in expression [{2}].", + error, colStr, text); + } + + function readNumber() { + var number = ""; + var start = index; + while (index < text.length) { + var ch = lowercase(text.charAt(index)); + if (ch == '.' || isNumber(ch)) { + number += ch; + } else { + var peekCh = peek(); + if (ch == 'e' && isExpOperator(peekCh)) { + number += ch; + } else if (isExpOperator(ch) && + peekCh && isNumber(peekCh) && + number.charAt(number.length - 1) == 'e') { + number += ch; + } else if (isExpOperator(ch) && + (!peekCh || !isNumber(peekCh)) && + number.charAt(number.length - 1) == 'e') { + throwError('Invalid exponent'); } else { - Child = function() {}; // should be anonymous; This is so that when the minifier munges - // the name it does not become random set of chars. These will then show up as class - // name in the debugger. - Child.prototype = this; - child = new Child(); - child.$id = nextUid(); + break; } - child['this'] = child; - child.$$listeners = {}; - child.$parent = this; - child.$$asyncQueue = []; - child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; - child.$$prevSibling = this.$$childTail; - if (this.$$childHead) { - this.$$childTail.$$nextSibling = child; - this.$$childTail = child; + } + index++; + } + number = 1 * number; + tokens.push({index:start, text:number, json:true, + fn:function() {return number;}}); + } + function readIdent() { + var ident = "", + start = index, + lastDot, peekIndex, methodName, ch; + + while (index < text.length) { + ch = text.charAt(index); + if (ch == '.' || isIdent(ch) || isNumber(ch)) { + if (ch == '.') lastDot = index; + ident += ch; + } else { + break; + } + index++; + } + + //check if this is not a method invocation and if it is back out to last dot + if (lastDot) { + peekIndex = index; + while(peekIndex < text.length) { + ch = text.charAt(peekIndex); + if (ch == '(') { + methodName = ident.substr(lastDot - start + 1); + ident = ident.substr(0, lastDot - start); + index = peekIndex; + break; + } + if(isWhitespace(ch)) { + peekIndex++; } else { - this.$$childHead = this.$$childTail = child; + break; } - return child; - }, + } + } - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$watch - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Registers a `listener` callback to be executed whenever the `watchExpression` changes. - * - * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and - * should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()} - * reruns when it detects changes the `watchExpression` can execute multiple times per - * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) - * - The `listener` is called only when the value from the current `watchExpression` and the - * previous call to `watchExpression` are not equal (with the exception of the initial run, - * see below). The inequality is determined according to - * {@link angular.equals} function. To save the value of the object for later comparison, the - * {@link angular.copy} function is used. It also means that watching complex options will - * have adverse memory and performance implications. - * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This - * is achieved by rerunning the watchers until no changes are detected. The rerun iteration - * limit is 10 to prevent an infinite loop deadlock. - * - * - * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, - * you can register a `watchExpression` function with no `listener`. (Since `watchExpression` - * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is - * detected, be prepared for multiple calls to your listener.) - * - * After a watcher is registered with the scope, the `listener` fn is called asynchronously - * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the - * watcher. In rare cases, this is undesirable because the listener is called when the result - * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you - * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the - * listener was called due to initialization. - * - * - * # Example - *
-           // let's assume that scope was dependency injected as the $rootScope
-           var scope = $rootScope;
-           scope.name = 'misko';
-           scope.counter = 0;
 
-           expect(scope.counter).toEqual(0);
-           scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; });
-           expect(scope.counter).toEqual(0);
+    var token = {
+      index:start,
+      text:ident
+    };
 
-           scope.$digest();
-           // no variable change
-           expect(scope.counter).toEqual(0);
+    if (OPERATORS.hasOwnProperty(ident)) {
+      token.fn = token.json = OPERATORS[ident];
+    } else {
+      var getter = getterFn(ident, csp, text);
+      token.fn = extend(function(self, locals) {
+        return (getter(self, locals));
+      }, {
+        assign: function(self, value) {
+          return setter(self, ident, value, text);
+        }
+      });
+    }
 
-           scope.name = 'adam';
-           scope.$digest();
-           expect(scope.counter).toEqual(1);
-       * 
- * - * - * - * @param {(function()|string)} watchExpression Expression that is evaluated on each - * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a - * call to the `listener`. - * - * - `string`: Evaluated as {@link guide/expression expression} - * - `function(scope)`: called with current `scope` as a parameter. - * @param {(function()|string)=} listener Callback called whenever the return value of - * the `watchExpression` changes. - * - * - `string`: Evaluated as {@link guide/expression expression} - * - `function(newValue, oldValue, scope)`: called with current and previous values as parameters. - * - * @param {boolean=} objectEquality Compare object for equality rather than for reference. - * @returns {function()} Returns a deregistration function for this listener. - */ - $watch: function(watchExp, listener, objectEquality) { - var scope = this, - get = compileToFn(watchExp, 'watch'), - array = scope.$$watchers, - watcher = { - fn: listener, - last: initWatchVal, - get: get, - exp: watchExp, - eq: !!objectEquality - }; + tokens.push(token); - // in the case user pass string, we need to compile it, do we really need this ? - if (!isFunction(listener)) { - var listenFn = compileToFn(listener || noop, 'listener'); - watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; - } + if (methodName) { + tokens.push({ + index:lastDot, + text: '.', + json: false + }); + tokens.push({ + index: lastDot + 1, + text: methodName, + json: false + }); + } + } - if (!array) { - array = scope.$$watchers = []; + function readString(quote) { + var start = index; + index++; + var string = ""; + var rawString = quote; + var escape = false; + while (index < text.length) { + var ch = text.charAt(index); + rawString += ch; + if (escape) { + if (ch == 'u') { + var hex = text.substring(index + 1, index + 5); + if (!hex.match(/[\da-f]{4}/i)) + throwError( "Invalid unicode escape [\\u" + hex + "]"); + index += 4; + string += String.fromCharCode(parseInt(hex, 16)); + } else { + var rep = ESCAPE[ch]; + if (rep) { + string += rep; + } else { + string += ch; + } } - // we use unshift since we use a while loop in $digest for speed. - // the while loop reads in reverse order. - array.unshift(watcher); + escape = false; + } else if (ch == '\\') { + escape = true; + } else if (ch == quote) { + index++; + tokens.push({ + index:start, + text:rawString, + string:string, + json:true, + fn:function() { return string; } + }); + return; + } else { + string += ch; + } + index++; + } + throwError("Unterminated quote", start); + } +} - return function() { - arrayRemove(array, watcher); - }; - }, +///////////////////////////////////////// - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$digest - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children. - * Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the - * `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are - * firing. This means that it is possible to get into an infinite loop. This function will throw - * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10. - * - * Usually you don't call `$digest()` directly in - * {@link ng.directive:ngController controllers} or in - * {@link ng.$compileProvider#directive directives}. - * Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a - * {@link ng.$compileProvider#directive directives}) will force a `$digest()`. - * - * If you want to be notified whenever `$digest()` is called, - * you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()} - * with no `listener`. - * - * You may have a need to call `$digest()` from within unit-tests, to simulate the scope - * life-cycle. - * - * # Example - *
-           var scope = ...;
-           scope.name = 'misko';
-           scope.counter = 0;
+function parser(text, json, $filter, csp){
+  var ZERO = valueFn(0),
+      value,
+      tokens = lex(text, csp),
+      assignment = _assignment,
+      functionCall = _functionCall,
+      fieldAccess = _fieldAccess,
+      objectIndex = _objectIndex,
+      filterChain = _filterChain;
+
+  if(json){
+    // The extra level of aliasing is here, just in case the lexer misses something, so that
+    // we prevent any accidental execution in JSON.
+    assignment = logicalOR;
+    functionCall =
+      fieldAccess =
+      objectIndex =
+      filterChain =
+        function() { throwError("is not valid json", {text:text, index:0}); };
+    value = primary();
+  } else {
+    value = statements();
+  }
+  if (tokens.length !== 0) {
+    throwError("is an unexpected token", tokens[0]);
+  }
+  value.literal = !!value.literal;
+  value.constant = !!value.constant;
+  return value;
+
+  ///////////////////////////////////
+  function throwError(msg, token) {
+    throw $parseMinErr('syntax',
+        "Syntax Error: Token '{0}' {1} at column {2} of the expression [{3}] starting at [{4}].",
+        token.text, msg, (token.index + 1), text, text.substring(token.index));
+  }
+
+  function peekToken() {
+    if (tokens.length === 0)
+      throw $parseMinErr('ueoe', "Unexpected end of expression: {0}", text);
+    return tokens[0];
+  }
+
+  function peek(e1, e2, e3, e4) {
+    if (tokens.length > 0) {
+      var token = tokens[0];
+      var t = token.text;
+      if (t==e1 || t==e2 || t==e3 || t==e4 ||
+          (!e1 && !e2 && !e3 && !e4)) {
+        return token;
+      }
+    }
+    return false;
+  }
 
-           expect(scope.counter).toEqual(0);
-           scope.$watch('name', function(newValue, oldValue) {
-             scope.counter = scope.counter + 1;
-           });
-           expect(scope.counter).toEqual(0);
+  function expect(e1, e2, e3, e4){
+    var token = peek(e1, e2, e3, e4);
+    if (token) {
+      if (json && !token.json) {
+        throwError("is not valid json", token);
+      }
+      tokens.shift();
+      return token;
+    }
+    return false;
+  }
 
-           scope.$digest();
-           // no variable change
-           expect(scope.counter).toEqual(0);
+  function consume(e1){
+    if (!expect(e1)) {
+      throwError("is unexpected, expecting [" + e1 + "]", peek());
+    }
+  }
 
-           scope.name = 'adam';
-           scope.$digest();
-           expect(scope.counter).toEqual(1);
-       * 
- * - */ - $digest: function() { - var watch, value, last, - watchers, - asyncQueue, - length, - dirty, ttl = TTL, - next, current, target = this, - watchLog = [], - logIdx, logMsg; + function unaryFn(fn, right) { + return extend(function(self, locals) { + return fn(self, locals, right); + }, { + constant:right.constant + }); + } - beginPhase('$digest'); + function ternaryFn(left, middle, right){ + return extend(function(self, locals){ + return left(self, locals) ? middle(self, locals) : right(self, locals); + }, { + constant: left.constant && middle.constant && right.constant + }); + } - do { - dirty = false; - current = target; - do { - asyncQueue = current.$$asyncQueue; - while(asyncQueue.length) { - try { - current.$eval(asyncQueue.shift()); - } catch (e) { - $exceptionHandler(e); - } - } - if ((watchers = current.$$watchers)) { - // process our watches - length = watchers.length; - while (length--) { - try { - watch = watchers[length]; - // Most common watches are on primitives, in which case we can short - // circuit it with === operator, only when === fails do we use .equals - if ((value = watch.get(current)) !== (last = watch.last) && - !(watch.eq - ? equals(value, last) - : (typeof value == 'number' && typeof last == 'number' - && isNaN(value) && isNaN(last)))) { - dirty = true; - watch.last = watch.eq ? copy(value) : value; - watch.fn(value, ((last === initWatchVal) ? value : last), current); - if (ttl < 5) { - logIdx = 4 - ttl; - if (!watchLog[logIdx]) watchLog[logIdx] = []; - logMsg = (isFunction(watch.exp)) - ? 'fn: ' + (watch.exp.name || watch.exp.toString()) - : watch.exp; - logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); - watchLog[logIdx].push(logMsg); - } - } - } catch (e) { - $exceptionHandler(e); - } - } - } + function binaryFn(left, fn, right) { + return extend(function(self, locals) { + return fn(self, locals, left, right); + }, { + constant:left.constant && right.constant + }); + } - // Insanity Warning: scope depth-first traversal - // yes, this code is a bit crazy, but it works and we have tests to prove it! - // this piece should be kept in sync with the traversal in $broadcast - if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { - while(current !== target && !(next = current.$$nextSibling)) { - current = current.$parent; - } + function statements() { + var statements = []; + while(true) { + if (tokens.length > 0 && !peek('}', ')', ';', ']')) + statements.push(filterChain()); + if (!expect(';')) { + // optimize for the common case where there is only one statement. + // TODO(size): maybe we should not support multiple statements? + return statements.length == 1 + ? statements[0] + : function(self, locals){ + var value; + for ( var i = 0; i < statements.length; i++) { + var statement = statements[i]; + if (statement) + value = statement(self, locals); } - } while ((current = next)); - - if(dirty && !(ttl--)) { - clearPhase(); - throw Error(TTL + ' $digest() iterations reached. Aborting!\n' + - 'Watchers fired in the last 5 iterations: ' + toJson(watchLog)); - } - } while (dirty || asyncQueue.length); - - clearPhase(); - }, + return value; + }; + } + } + } + function _filterChain() { + var left = expression(); + var token; + while(true) { + if ((token = expect('|'))) { + left = binaryFn(left, token.fn, filter()); + } else { + return left; + } + } + } - /** - * @ngdoc event - * @name ng.$rootScope.Scope#$destroy - * @eventOf ng.$rootScope.Scope - * @eventType broadcast on scope being destroyed - * - * @description - * Broadcasted when a scope and its children are being destroyed. - */ + function filter() { + var token = expect(); + var fn = $filter(token.text); + var argsFn = []; + while(true) { + if ((token = expect(':'))) { + argsFn.push(expression()); + } else { + var fnInvoke = function(self, locals, input){ + var args = [input]; + for ( var i = 0; i < argsFn.length; i++) { + args.push(argsFn[i](self, locals)); + } + return fn.apply(self, args); + }; + return function() { + return fnInvoke; + }; + } + } + } - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$destroy - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Removes the current scope (and all of its children) from the parent scope. Removal implies - * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer - * propagate to the current scope and its children. Removal also implies that the current - * scope is eligible for garbage collection. - * - * The `$destroy()` is usually used by directives such as - * {@link ng.directive:ngRepeat ngRepeat} for managing the - * unrolling of the loop. - * - * Just before a scope is destroyed a `$destroy` event is broadcasted on this scope. - * Application code can register a `$destroy` event handler that will give it chance to - * perform any necessary cleanup. - */ - $destroy: function() { - // we can't destroy the root scope or a scope that has been already destroyed - if ($rootScope == this || this.$$destroyed) return; - var parent = this.$parent; + function expression() { + return assignment(); + } - this.$broadcast('$destroy'); - this.$$destroyed = true; + function _assignment() { + var left = ternary(); + var right; + var token; + if ((token = expect('='))) { + if (!left.assign) { + throwError("implies assignment but [" + + text.substring(0, token.index) + "] can not be assigned to", token); + } + right = ternary(); + return function(scope, locals){ + return left.assign(scope, right(scope, locals), locals); + }; + } else { + return left; + } + } - if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; - if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; - if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; - if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; + function ternary() { + var left = logicalOR(); + var middle; + var token; + if((token = expect('?'))){ + middle = ternary(); + if((token = expect(':'))){ + return ternaryFn(left, middle, ternary()); + } + else { + throwError('expected :', token); + } + } + else { + return left; + } + } - // This is bogus code that works around Chrome's GC leak - // see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 - this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = - this.$$childTail = null; - }, + function logicalOR() { + var left = logicalAND(); + var token; + while(true) { + if ((token = expect('||'))) { + left = binaryFn(left, token.fn, logicalAND()); + } else { + return left; + } + } + } - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$eval - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Executes the `expression` on the current scope returning the result. Any exceptions in the - * expression are propagated (uncaught). This is useful when evaluating Angular expressions. - * - * # Example - *
-           var scope = ng.$rootScope.Scope();
-           scope.a = 1;
-           scope.b = 2;
+  function logicalAND() {
+    var left = equality();
+    var token;
+    if ((token = expect('&&'))) {
+      left = binaryFn(left, token.fn, logicalAND());
+    }
+    return left;
+  }
 
-           expect(scope.$eval('a+b')).toEqual(3);
-           expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
-       * 
- * - * @param {(string|function())=} expression An angular expression to be executed. - * - * - `string`: execute using the rules as defined in {@link guide/expression expression}. - * - `function(scope)`: execute the function with the current `scope` parameter. - * - * @returns {*} The result of evaluating the expression. - */ - $eval: function(expr, locals) { - return $parse(expr)(this, locals); - }, + function equality() { + var left = relational(); + var token; + if ((token = expect('==','!=','===','!=='))) { + left = binaryFn(left, token.fn, equality()); + } + return left; + } - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$evalAsync - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Executes the expression on the current scope at a later point in time. - * - * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that: - * - * - it will execute in the current script execution context (before any DOM rendering). - * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after - * `expression` execution. - * - * Any exceptions from the execution of the expression are forwarded to the - * {@link ng.$exceptionHandler $exceptionHandler} service. - * - * @param {(string|function())=} expression An angular expression to be executed. - * - * - `string`: execute using the rules as defined in {@link guide/expression expression}. - * - `function(scope)`: execute the function with the current `scope` parameter. - * - */ - $evalAsync: function(expr) { - this.$$asyncQueue.push(expr); - }, + function relational() { + var left = additive(); + var token; + if ((token = expect('<', '>', '<=', '>='))) { + left = binaryFn(left, token.fn, relational()); + } + return left; + } - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$apply - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * `$apply()` is used to execute an expression in angular from outside of the angular framework. - * (For example from browser DOM events, setTimeout, XHR or third party libraries). - * Because we are calling into the angular framework we need to perform proper scope life-cycle - * of {@link ng.$exceptionHandler exception handling}, - * {@link ng.$rootScope.Scope#$digest executing watches}. - * - * ## Life cycle - * - * # Pseudo-Code of `$apply()` - *
-           function $apply(expr) {
-             try {
-               return $eval(expr);
-             } catch (e) {
-               $exceptionHandler(e);
-             } finally {
-               $root.$digest();
-             }
-           }
-       * 
- * - * - * Scope's `$apply()` method transitions through the following stages: - * - * 1. The {@link guide/expression expression} is executed using the - * {@link ng.$rootScope.Scope#$eval $eval()} method. - * 2. Any exceptions from the execution of the expression are forwarded to the - * {@link ng.$exceptionHandler $exceptionHandler} service. - * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression - * was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. - * - * - * @param {(string|function())=} exp An angular expression to be executed. - * - * - `string`: execute using the rules as defined in {@link guide/expression expression}. - * - `function(scope)`: execute the function with current `scope` parameter. - * - * @returns {*} The result of evaluating the expression. - */ - $apply: function(expr) { - try { - beginPhase('$apply'); - return this.$eval(expr); - } catch (e) { - $exceptionHandler(e); - } finally { - clearPhase(); - try { - $rootScope.$digest(); - } catch (e) { - $exceptionHandler(e); - throw e; - } - } - }, + function additive() { + var left = multiplicative(); + var token; + while ((token = expect('+','-'))) { + left = binaryFn(left, token.fn, multiplicative()); + } + return left; + } - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$on - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of - * event life cycle. - * - * The event listener function format is: `function(event, args...)`. The `event` object - * passed into the listener has the following attributes: - * - * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or `$broadcast`-ed. - * - `currentScope` - `{Scope}`: the current scope which is handling the event. - * - `name` - `{string}`: Name of the event. - * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel further event - * propagation (available only for events that were `$emit`-ed). - * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag to true. - * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. - * - * @param {string} name Event name to listen on. - * @param {function(event, args...)} listener Function to call when the event is emitted. - * @returns {function()} Returns a deregistration function for this listener. - */ - $on: function(name, listener) { - var namedListeners = this.$$listeners[name]; - if (!namedListeners) { - this.$$listeners[name] = namedListeners = []; - } - namedListeners.push(listener); + function multiplicative() { + var left = unary(); + var token; + while ((token = expect('*','/','%'))) { + left = binaryFn(left, token.fn, unary()); + } + return left; + } - return function() { - namedListeners[indexOf(namedListeners, listener)] = null; - }; - }, + function unary() { + var token; + if (expect('+')) { + return primary(); + } else if ((token = expect('-'))) { + return binaryFn(ZERO, token.fn, unary()); + } else if ((token = expect('!'))) { + return unaryFn(token.fn, unary()); + } else { + return primary(); + } + } - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$emit - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Dispatches an event `name` upwards through the scope hierarchy notifying the - * registered {@link ng.$rootScope.Scope#$on} listeners. - * - * The event life cycle starts at the scope on which `$emit` was called. All - * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. - * Afterwards, the event traverses upwards toward the root scope and calls all registered - * listeners along the way. The event will stop propagating if one of the listeners cancels it. - * - * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed - * onto the {@link ng.$exceptionHandler $exceptionHandler} service. - * - * @param {string} name Event name to emit. - * @param {...*} args Optional set of arguments which will be passed onto the event listeners. - * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} - */ - $emit: function(name, args) { - var empty = [], - namedListeners, - scope = this, - stopPropagation = false, - event = { - name: name, - targetScope: scope, - stopPropagation: function() {stopPropagation = true;}, - preventDefault: function() { - event.defaultPrevented = true; - }, - defaultPrevented: false - }, - listenerArgs = concat([event], arguments, 1), - i, length; + function primary() { + var primary; + if (expect('(')) { + primary = filterChain(); + consume(')'); + } else if (expect('[')) { + primary = arrayDeclaration(); + } else if (expect('{')) { + primary = object(); + } else { + var token = expect(); + primary = token.fn; + if (!primary) { + throwError("not a primary expression", token); + } + if (token.json) { + primary.constant = primary.literal = true; + } + } + + var next, context; + while ((next = expect('(', '[', '.'))) { + if (next.text === '(') { + primary = functionCall(primary, context); + context = null; + } else if (next.text === '[') { + context = primary; + primary = objectIndex(primary); + } else if (next.text === '.') { + context = primary; + primary = fieldAccess(primary); + } else { + throwError("IMPOSSIBLE"); + } + } + return primary; + } - do { - namedListeners = scope.$$listeners[name] || empty; - event.currentScope = scope; - for (i=0, length=namedListeners.length; i 1; i++) { + key = ensureSafeMemberName(element.shift(), fullExp); + var propertyObj = obj[key]; + if (!propertyObj) { + propertyObj = {}; + obj[key] = propertyObj; + } + obj = propertyObj; + if (obj.then) { + if (!("$$v" in obj)) { + (function(promise) { + promise.then(function(val) { promise.$$v = val; }); } + )(obj); + } + if (obj.$$v === undefined) { + obj.$$v = {}; + } + obj = obj.$$v; + } + } + key = ensureSafeMemberName(element.shift(), fullExp); + obj[key] = setValue; + return setValue; +} - return event; +var getterFnCache = {}; + +/** + * Implementation of the "Black Hole" variant from: + * - http://jsperf.com/angularjs-parse-getter/4 + * - http://jsperf.com/path-evaluation-simplified/7 + */ +function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp) { + ensureSafeMemberName(key0, fullExp); + ensureSafeMemberName(key1, fullExp); + ensureSafeMemberName(key2, fullExp); + ensureSafeMemberName(key3, fullExp); + ensureSafeMemberName(key4, fullExp); + return function(scope, locals) { + var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, + promise; + + if (pathVal === null || pathVal === undefined) return pathVal; + + pathVal = pathVal[key0]; + if (pathVal && pathVal.then) { + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = val; }); } - }; + pathVal = pathVal.$$v; + } + if (!key1 || pathVal === null || pathVal === undefined) return pathVal; - var $rootScope = new Scope(); + pathVal = pathVal[key1]; + if (pathVal && pathVal.then) { + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = val; }); + } + pathVal = pathVal.$$v; + } + if (!key2 || pathVal === null || pathVal === undefined) return pathVal; - return $rootScope; + pathVal = pathVal[key2]; + if (pathVal && pathVal.then) { + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = val; }); + } + pathVal = pathVal.$$v; + } + if (!key3 || pathVal === null || pathVal === undefined) return pathVal; + pathVal = pathVal[key3]; + if (pathVal && pathVal.then) { + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = val; }); + } + pathVal = pathVal.$$v; + } + if (!key4 || pathVal === null || pathVal === undefined) return pathVal; - function beginPhase(phase) { - if ($rootScope.$$phase) { - throw Error($rootScope.$$phase + ' already in progress'); + pathVal = pathVal[key4]; + if (pathVal && pathVal.then) { + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = val; }); } - - $rootScope.$$phase = phase; + pathVal = pathVal.$$v; } + return pathVal; + }; +} - function clearPhase() { - $rootScope.$$phase = null; - } +function getterFn(path, csp, fullExp) { + if (getterFnCache.hasOwnProperty(path)) { + return getterFnCache[path]; + } - function compileToFn(exp, name) { - var fn = $parse(exp); - assertArgFn(fn, name); - return fn; - } + var pathKeys = path.split('.'), + pathKeysLength = pathKeys.length, + fn; - /** - * function used as an initial value for watchers. - * because it's unique we can easily tell it apart from other values - */ - function initWatchVal() {} - }]; + if (csp) { + fn = (pathKeysLength < 6) + ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp) + : function(scope, locals) { + var i = 0, val; + do { + val = cspSafeGetterFn( + pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], fullExp + )(scope, locals); + + locals = undefined; // clear after first iteration + scope = val; + } while (i < pathKeysLength); + return val; + } + } else { + var code = 'var l, fn, p;\n'; + forEach(pathKeys, function(key, index) { + ensureSafeMemberName(key, fullExp); + code += 'if(s === null || s === undefined) return s;\n' + + 'l=s;\n' + + 's='+ (index + // we simply dereference 's' on any .dot notation + ? 's' + // but if we are first then we check locals first, and if so read it first + : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' + + 'if (s && s.then) {\n' + + ' if (!("$$v" in s)) {\n' + + ' p=s;\n' + + ' p.$$v = undefined;\n' + + ' p.then(function(v) {p.$$v=v;});\n' + + '}\n' + + ' s=s.$$v\n' + + '}\n'; + }); + code += 'return s;'; + fn = Function('s', 'k', code); // s=scope, k=locals + fn.toString = function() { return code; }; + } + + return getterFnCache[path] = fn; } +/////////////////////////////////// + /** - * !!! This is an undocumented "private" service !!! + * @ngdoc function + * @name ng.$parse + * @function * - * @name ng.$sniffer - * @requires $window + * @description * - * @property {boolean} history Does the browser support html5 history api ? - * @property {boolean} hashchange Does the browser support hashchange event ? + * Converts Angular {@link guide/expression expression} into a function. + * + *
+ *   var getter = $parse('user.name');
+ *   var setter = getter.assign;
+ *   var context = {user:{name:'angular'}};
+ *   var locals = {user:{name:'local'}};
+ *
+ *   expect(getter(context)).toEqual('angular');
+ *   setter(context, 'newValue');
+ *   expect(context.user.name).toEqual('newValue');
+ *   expect(getter(context, locals)).toEqual('local');
+ * 
+ * + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + * + * The returned function also has the following properties: + * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript + * literal. + * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript + * constant literals. + * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be + * set to a function to change its value on the given context. * - * @description - * This is very simple implementation of testing browser's features. */ -function $SnifferProvider() { - this.$get = ['$window', function($window) { - var eventSupport = {}, - android = int((/android (\d+)/.exec(lowercase($window.navigator.userAgent)) || [])[1]); - - return { - // Android has history.pushState, but it does not update location correctly - // so let's not use the history API at all. - // http://code.google.com/p/android/issues/detail?id=17471 - // https://github.com/angular/angular.js/issues/904 - history: !!($window.history && $window.history.pushState && !(android < 4)), - hashchange: 'onhashchange' in $window && - // IE8 compatible mode lies - (!$window.document.documentMode || $window.document.documentMode > 7), - hasEvent: function(event) { - // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have - // it. In particular the event is not fired when backspace or delete key are pressed or - // when cut operation is performed. - if (event == 'input' && msie == 9) return false; - - if (isUndefined(eventSupport[event])) { - var divElm = $window.document.createElement('div'); - eventSupport[event] = 'on' + event in divElm; - } - - return eventSupport[event]; - }, - // TODO(i): currently there is no way to feature detect CSP without triggering alerts - csp: false +function $ParseProvider() { + var cache = {}; + this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { + return function(exp) { + switch(typeof exp) { + case 'string': + return cache.hasOwnProperty(exp) + ? cache[exp] + : cache[exp] = parser(exp, false, $filter, $sniffer.csp); + case 'function': + return exp; + default: + return noop; + } }; }]; } /** - * @ngdoc object - * @name ng.$window + * @ngdoc service + * @name ng.$q + * @requires $rootScope + * + * @description + * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). + * + * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an + * interface for interacting with an object that represents the result of an action that is + * performed asynchronously, and may or may not be finished at any given point in time. + * + * From the perspective of dealing with error handling, deferred and promise APIs are to + * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. + * + *
+ *   // for the purpose of this example let's assume that variables `$q` and `scope` are
+ *   // available in the current lexical scope (they could have been injected or passed in).
+ *
+ *   function asyncGreet(name) {
+ *     var deferred = $q.defer();
+ *
+ *     setTimeout(function() {
+ *       // since this fn executes async in a future turn of the event loop, we need to wrap
+ *       // our code into an $apply call so that the model changes are properly observed.
+ *       scope.$apply(function() {
+ *         if (okToGreet(name)) {
+ *           deferred.resolve('Hello, ' + name + '!');
+ *         } else {
+ *           deferred.reject('Greeting ' + name + ' is not allowed.');
+ *         }
+ *       });
+ *     }, 1000);
+ *
+ *     return deferred.promise;
+ *   }
+ *
+ *   var promise = asyncGreet('Robin Hood');
+ *   promise.then(function(greeting) {
+ *     alert('Success: ' + greeting);
+ *   }, function(reason) {
+ *     alert('Failed: ' + reason);
+ *   });
+ * 
+ * + * At first it might not be obvious why this extra complexity is worth the trouble. The payoff + * comes in the way of + * [guarantees that promise and deferred APIs make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md). + * + * Additionally the promise api allows for composition that is very hard to do with the + * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. + * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the + * section on serial or parallel joining of promises. + * + * + * # The Deferred API + * + * A new instance of deferred is constructed by calling `$q.defer()`. + * + * The purpose of the deferred object is to expose the associated Promise instance as well as APIs + * that can be used for signaling the successful or unsuccessful completion of the task. + * + * **Methods** + * + * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection + * constructed via `$q.reject`, the promise will be rejected instead. + * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to + * resolving it with a rejection constructed via `$q.reject`. + * + * **Properties** + * + * - promise – `{Promise}` – promise object associated with this deferred. + * + * + * # The Promise API + * + * A new promise instance is created when a deferred instance is created and can be retrieved by + * calling `deferred.promise`. + * + * The purpose of the promise object is to allow for interested parties to get access to the result + * of the deferred task when it completes. + * + * **Methods** + * + * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved + * or rejected, `then` calls one of the success or error callbacks asynchronously as soon as the result + * is available. The callbacks are called with a single argument: the result or rejection reason. + * + * This method *returns a new promise* which is resolved or rejected via the return value of the + * `successCallback` or `errorCallback`. + * + * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` + * + * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise, + * but to do so without modifying the final value. This is useful to release resources or do some + * clean-up that needs to be done whether the promise was rejected or resolved. See the [full + * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for + * more information. + * + * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as + * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to + * make your code IE8 compatible. + * + * # Chaining promises + * + * Because calling the `then` method of a promise returns a new derived promise, it is easily possible + * to create a chain of promises: + * + *
+ *   promiseB = promiseA.then(function(result) {
+ *     return result + 1;
+ *   });
+ *
+ *   // promiseB will be resolved immediately after promiseA is resolved and its value
+ *   // will be the result of promiseA incremented by 1
+ * 
+ * + * It is possible to create chains of any length and since a promise can be resolved with another + * promise (which will defer its resolution further), it is possible to pause/defer resolution of + * the promises at any point in the chain. This makes it possible to implement powerful APIs like + * $http's response interceptors. + * + * + * # Differences between Kris Kowal's Q and $q + * + * There are three main differences: * - * @description - * A reference to the browser's `window` object. While `window` - * is globally available in JavaScript, it causes testability problems, because - * it is a global variable. In angular we always refer to it through the - * `$window` service, so it may be overriden, removed or mocked for testing. + * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation + * mechanism in angular, which means faster propagation of resolution or rejection into your + * models and avoiding unnecessary browser repaints, which would result in flickering UI. + * - $q promises are recognized by the templating engine in angular, which means that in templates + * you can treat promises attached to a scope as if they were the resulting values. + * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains + * all the important functionality needed for common async tasks. * - * All expressions are evaluated with respect to current scope so they don't - * suffer from window globality. + * # Testing * - * @example - - - -
- - -
-
- - it('should display the greeting in the input box', function() { - input('greeting').enter('Hello, E2E Tests'); - // If we click the button it will block the test runner - // element(':button').click(); - }); - -
+ *
+ *    it('should simulate promise', inject(function($q, $rootScope) {
+ *      var deferred = $q.defer();
+ *      var promise = deferred.promise;
+ *      var resolvedValue;
+ *
+ *      promise.then(function(value) { resolvedValue = value; });
+ *      expect(resolvedValue).toBeUndefined();
+ *
+ *      // Simulate resolving of promise
+ *      deferred.resolve(123);
+ *      // Note that the 'then' function does not get called synchronously.
+ *      // This is because we want the promise API to always be async, whether or not
+ *      // it got called synchronously or asynchronously.
+ *      expect(resolvedValue).toBeUndefined();
+ *
+ *      // Propagate promise resolution to 'then' functions using $apply().
+ *      $rootScope.$apply();
+ *      expect(resolvedValue).toEqual(123);
+ *    });
+ *  
*/ -function $WindowProvider(){ - this.$get = valueFn(window); +function $QProvider() { + + this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { + return qFactory(function(callback) { + $rootScope.$evalAsync(callback); + }, $exceptionHandler); + }]; } + /** - * Parse headers into key value object + * Constructs a promise manager. * - * @param {string} headers Raw headers as a string - * @returns {Object} Parsed headers as key value object + * @param {function(function)} nextTick Function for executing functions in the next turn. + * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for + * debugging purposes. + * @returns {object} Promise manager. */ -function parseHeaders(headers) { - var parsed = {}, key, val, i; +function qFactory(nextTick, exceptionHandler) { - if (!headers) return parsed; + /** + * @ngdoc + * @name ng.$q#defer + * @methodOf ng.$q + * @description + * Creates a `Deferred` object which represents a task which will finish in the future. + * + * @returns {Deferred} Returns a new instance of deferred. + */ + var defer = function() { + var pending = [], + value, deferred; - forEach(headers.split('\n'), function(line) { - i = line.indexOf(':'); - key = lowercase(trim(line.substr(0, i))); - val = trim(line.substr(i + 1)); + deferred = { - if (key) { - if (parsed[key]) { - parsed[key] += ', ' + val; - } else { - parsed[key] = val; - } - } - }); + resolve: function(val) { + if (pending) { + var callbacks = pending; + pending = undefined; + value = ref(val); - return parsed; -} + if (callbacks.length) { + nextTick(function() { + var callback; + for (var i = 0, ii = callbacks.length; i < ii; i++) { + callback = callbacks[i]; + value.then(callback[0], callback[1], callback[2]); + } + }); + } + } + }, -/** - * Returns a function that provides access to parsed headers. - * - * Headers are lazy parsed when first requested. - * @see parseHeaders - * - * @param {(string|Object)} headers Headers to provide access to. - * @returns {function(string=)} Returns a getter function which if called with: - * - * - if called with single an argument returns a single header value or null - * - if called with no arguments returns an object containing all headers. - */ -function headersGetter(headers) { - var headersObj = isObject(headers) ? headers : undefined; + reject: function(reason) { + deferred.resolve(reject(reason)); + }, - return function(name) { - if (!headersObj) headersObj = parseHeaders(headers); - if (name) { - return headersObj[lowercase(name)] || null; - } + notify: function(progress) { + if (pending) { + var callbacks = pending; - return headersObj; - }; -} + if (pending.length) { + nextTick(function() { + var callback; + for (var i = 0, ii = callbacks.length; i < ii; i++) { + callback = callbacks[i]; + callback[2](progress); + } + }); + } + } + }, -/** - * Chain all given functions - * - * This function is used for both request and response transforming - * - * @param {*} data Data to transform. - * @param {function(string=)} headers Http headers getter fn. - * @param {(function|Array.)} fns Function or an array of functions. - * @returns {*} Transformed data. - */ -function transformData(data, headers, fns) { - if (isFunction(fns)) - return fns(data, headers); + promise: { + then: function(callback, errback, progressback) { + var result = defer(); - forEach(fns, function(fn) { - data = fn(data, headers); - }); + var wrappedCallback = function(value) { + try { + result.resolve((callback || defaultCallback)(value)); + } catch(e) { + result.reject(e); + exceptionHandler(e); + } + }; - return data; -} + var wrappedErrback = function(reason) { + try { + result.resolve((errback || defaultErrback)(reason)); + } catch(e) { + result.reject(e); + exceptionHandler(e); + } + }; + + var wrappedProgressback = function(progress) { + try { + result.notify((progressback || defaultCallback)(progress)); + } catch(e) { + exceptionHandler(e); + } + }; + if (pending) { + pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]); + } else { + value.then(wrappedCallback, wrappedErrback, wrappedProgressback); + } -function isSuccess(status) { - return 200 <= status && status < 300; -} + return result.promise; + }, + "catch": function(callback) { + return this.then(null, callback); + }, -function $HttpProvider() { - var JSON_START = /^\s*(\[|\{[^\{])/, - JSON_END = /[\}\]]\s*$/, - PROTECTION_PREFIX = /^\)\]\}',?\n/; + "finally": function(callback) { - var $config = this.defaults = { - // transform incoming response data - transformResponse: [function(data) { - if (isString(data)) { - // strip json vulnerability protection prefix - data = data.replace(PROTECTION_PREFIX, ''); - if (JSON_START.test(data) && JSON_END.test(data)) - data = fromJson(data, true); + function makePromise(value, resolved) { + var result = defer(); + if (resolved) { + result.resolve(value); + } else { + result.reject(value); + } + return result.promise; + } + + function handleCallback(value, isResolved) { + var callbackOutput = null; + try { + callbackOutput = (callback ||defaultCallback)(); + } catch(e) { + return makePromise(e, false); + } + if (callbackOutput && callbackOutput.then) { + return callbackOutput.then(function() { + return makePromise(value, isResolved); + }, function(error) { + return makePromise(error, false); + }); + } else { + return makePromise(value, isResolved); + } + } + + return this.then(function(value) { + return handleCallback(value, true); + }, function(error) { + return handleCallback(error, false); + }); + } } - return data; - }], + }; - // transform outgoing request data - transformRequest: [function(d) { - return isObject(d) && !isFile(d) ? toJson(d) : d; - }], + return deferred; + }; - // default headers - headers: { - common: { - 'Accept': 'application/json, text/plain, */*', - 'X-Requested-With': 'XMLHttpRequest' - }, - post: {'Content-Type': 'application/json;charset=utf-8'}, - put: {'Content-Type': 'application/json;charset=utf-8'} - } + + var ref = function(value) { + if (value && value.then) return value; + return { + then: function(callback) { + var result = defer(); + nextTick(function() { + result.resolve(callback(value)); + }); + return result.promise; + } + }; }; - var providerResponseInterceptors = this.responseInterceptors = []; - - this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', - function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { - var defaultCache = $cacheFactory('$http'), - responseInterceptors = []; - - forEach(providerResponseInterceptors, function(interceptor) { - responseInterceptors.push( - isString(interceptor) - ? $injector.get(interceptor) - : $injector.invoke(interceptor) - ); - }); + /** + * @ngdoc + * @name ng.$q#reject + * @methodOf ng.$q + * @description + * Creates a promise that is resolved as rejected with the specified `reason`. This api should be + * used to forward rejection in a chain of promises. If you are dealing with the last promise in + * a promise chain, you don't need to worry about it. + * + * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of + * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via + * a promise error callback and you want to forward the error to the promise derived from the + * current promise, you have to "rethrow" the error by returning a rejection constructed via + * `reject`. + * + *
+   *   promiseB = promiseA.then(function(result) {
+   *     // success: do something and resolve promiseB
+   *     //          with the old or a new result
+   *     return result;
+   *   }, function(reason) {
+   *     // error: handle the error if possible and
+   *     //        resolve promiseB with newPromiseOrValue,
+   *     //        otherwise forward the rejection to promiseB
+   *     if (canHandle(reason)) {
+   *      // handle the error and recover
+   *      return newPromiseOrValue;
+   *     }
+   *     return $q.reject(reason);
+   *   });
+   * 
+ * + * @param {*} reason Constant, message, exception or an object representing the rejection reason. + * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. + */ + var reject = function(reason) { + return { + then: function(callback, errback) { + var result = defer(); + nextTick(function() { + result.resolve((errback || defaultErrback)(reason)); + }); + return result.promise; + } + }; + }; - /** - * @ngdoc function - * @name ng.$http - * @requires $httpBackend - * @requires $browser - * @requires $cacheFactory - * @requires $rootScope - * @requires $q - * @requires $injector - * - * @description - * The `$http` service is a core Angular service that facilitates communication with the remote - * HTTP servers via the browser's {@link https://developer.mozilla.org/en/xmlhttprequest - * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}. - * - * For unit testing applications that use `$http` service, see - * {@link ngMock.$httpBackend $httpBackend mock}. - * - * For a higher level of abstraction, please check out the {@link ngResource.$resource - * $resource} service. - * - * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by - * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage - * it is important to familiarize yourself with these APIs and the guarantees they provide. - * - * - * # General usage - * The `$http` service is a function which takes a single argument — a configuration object — - * that is used to generate an HTTP request and returns a {@link ng.$q promise} - * with two $http specific methods: `success` and `error`. - * - *
-     *   $http({method: 'GET', url: '/someUrl'}).
-     *     success(function(data, status, headers, config) {
-     *       // this callback will be called asynchronously
-     *       // when the response is available
-     *     }).
-     *     error(function(data, status, headers, config) {
-     *       // called asynchronously if an error occurs
-     *       // or server returns response with an error status.
-     *     });
-     * 
- * - * Since the returned value of calling the $http function is a `promise`, you can also use - * the `then` method to register callbacks, and these callbacks will receive a single argument – - * an object representing the response. See the API signature and type info below for more - * details. - * - * A response status code between 200 and 299 is considered a success status and - * will result in the success callback being called. Note that if the response is a redirect, - * XMLHttpRequest will transparently follow it, meaning that the error callback will not be - * called for such responses. - * - * # Shortcut methods - * - * Since all invocations of the $http service require passing in an HTTP method and URL, and - * POST/PUT requests require request data to be provided as well, shortcut methods - * were created: - * - *
-     *   $http.get('/someUrl').success(successCallback);
-     *   $http.post('/someUrl', data).success(successCallback);
-     * 
- * - * Complete list of shortcut methods: - * - * - {@link ng.$http#get $http.get} - * - {@link ng.$http#head $http.head} - * - {@link ng.$http#post $http.post} - * - {@link ng.$http#put $http.put} - * - {@link ng.$http#delete $http.delete} - * - {@link ng.$http#jsonp $http.jsonp} - * - * - * # Setting HTTP Headers - * - * The $http service will automatically add certain HTTP headers to all requests. These defaults - * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration - * object, which currently contains this default configuration: - * - * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): - * - `Accept: application/json, text/plain, * / *` - * - `X-Requested-With: XMLHttpRequest` - * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) - * - `Content-Type: application/json` - * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) - * - `Content-Type: application/json` - * - * To add or overwrite these defaults, simply add or remove a property from these configuration - * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object - * with the lowercased HTTP method name as the key, e.g. - * `$httpProvider.defaults.headers.get['My-Header']='value'`. - * - * Additionally, the defaults can be set at runtime via the `$http.defaults` object in the same - * fashion. - * - * - * # Transforming Requests and Responses - * - * Both requests and responses can be transformed using transform functions. By default, Angular - * applies these transformations: - * - * Request transformations: - * - * - If the `data` property of the request configuration object contains an object, serialize it into - * JSON format. - * - * Response transformations: - * - * - If XSRF prefix is detected, strip it (see Security Considerations section below). - * - If JSON response is detected, deserialize it using a JSON parser. - * - * To globally augment or override the default transforms, modify the `$httpProvider.defaults.transformRequest` and - * `$httpProvider.defaults.transformResponse` properties. These properties are by default an - * array of transform functions, which allows you to `push` or `unshift` a new transformation function into the - * transformation chain. You can also decide to completely override any default transformations by assigning your - * transformation functions to these properties directly without the array wrapper. - * - * Similarly, to locally override the request/response transforms, augment the `transformRequest` and/or - * `transformResponse` properties of the configuration object passed into `$http`. - * - * - * # Caching - * - * To enable caching, set the configuration property `cache` to `true`. When the cache is - * enabled, `$http` stores the response from the server in local cache. Next time the - * response is served from the cache without sending a request to the server. - * - * Note that even if the response is served from cache, delivery of the data is asynchronous in - * the same way that real requests are. - * - * If there are multiple GET requests for the same URL that should be cached using the same - * cache, but the cache is not populated yet, only one request to the server will be made and - * the remaining requests will be fulfilled using the response from the first request. - * - * - * # Response interceptors - * - * Before you start creating interceptors, be sure to understand the - * {@link ng.$q $q and deferred/promise APIs}. - * - * For purposes of global error handling, authentication or any kind of synchronous or - * asynchronous preprocessing of received responses, it is desirable to be able to intercept - * responses for http requests before they are handed over to the application code that - * initiated these requests. The response interceptors leverage the {@link ng.$q - * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. - * - * The interceptors are service factories that are registered with the $httpProvider by - * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and - * injected with dependencies (if specified) and returns the interceptor — a function that - * takes a {@link ng.$q promise} and returns the original or a new promise. - * - *
-     *   // register the interceptor as a service
-     *   $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
-     *     return function(promise) {
-     *       return promise.then(function(response) {
-     *         // do something on success
-     *       }, function(response) {
-     *         // do something on error
-     *         if (canRecover(response)) {
-     *           return responseOrNewPromise
-     *         }
-     *         return $q.reject(response);
-     *       });
-     *     }
-     *   });
-     *
-     *   $httpProvider.responseInterceptors.push('myHttpInterceptor');
-     *
-     *
-     *   // register the interceptor via an anonymous factory
-     *   $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
-     *     return function(promise) {
-     *       // same as above
-     *     }
-     *   });
-     * 
- * - * - * # Security Considerations - * - * When designing web applications, consider security threats from: - * - * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx - * JSON vulnerability} - * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} - * - * Both server and the client must cooperate in order to eliminate these threats. Angular comes - * pre-configured with strategies that address these issues, but for this to work backend server - * cooperation is required. - * - * ## JSON Vulnerability Protection + /** + * @ngdoc + * @name ng.$q#when + * @methodOf ng.$q + * @description + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. + * This is useful when you are dealing with an object that might or might not be a promise, or if + * the promise comes from a source that can't be trusted. + * + * @param {*} value Value or a promise + * @returns {Promise} Returns a promise of the passed value or promise + */ + var when = function(value, callback, errback, progressback) { + var result = defer(), + done; + + var wrappedCallback = function(value) { + try { + return (callback || defaultCallback)(value); + } catch (e) { + exceptionHandler(e); + return reject(e); + } + }; + + var wrappedErrback = function(reason) { + try { + return (errback || defaultErrback)(reason); + } catch (e) { + exceptionHandler(e); + return reject(e); + } + }; + + var wrappedProgressback = function(progress) { + try { + return (progressback || defaultCallback)(progress); + } catch (e) { + exceptionHandler(e); + } + }; + + nextTick(function() { + ref(value).then(function(value) { + if (done) return; + done = true; + result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback)); + }, function(reason) { + if (done) return; + done = true; + result.resolve(wrappedErrback(reason)); + }, function(progress) { + if (done) return; + result.notify(wrappedProgressback(progress)); + }); + }); + + return result.promise; + }; + + + function defaultCallback(value) { + return value; + } + + + function defaultErrback(reason) { + return reject(reason); + } + + + /** + * @ngdoc + * @name ng.$q#all + * @methodOf ng.$q + * @description + * Combines multiple promises into a single promise that is resolved when all of the input + * promises are resolved. + * + * @param {Array.|Object.} promises An array or hash of promises. + * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, + * each value corresponding to the promise at the same index/key in the `promises` array/hash. If any of + * the promises is resolved with a rejection, this resulting promise will be resolved with the + * same rejection. + */ + function all(promises) { + var deferred = defer(), + counter = 0, + results = isArray(promises) ? [] : {}; + + forEach(promises, function(promise, key) { + counter++; + ref(promise).then(function(value) { + if (results.hasOwnProperty(key)) return; + results[key] = value; + if (!(--counter)) deferred.resolve(results); + }, function(reason) { + if (results.hasOwnProperty(key)) return; + deferred.reject(reason); + }); + }); + + if (counter === 0) { + deferred.resolve(results); + } + + return deferred.promise; + } + + return { + defer: defer, + reject: reject, + when: when, + all: all + }; +} + +/** + * DESIGN NOTES + * + * The design decisions behind the scope are heavily favored for speed and memory consumption. + * + * The typical use of scope is to watch the expressions, which most of the time return the same + * value as last time so we optimize the operation. + * + * Closures construction is expensive in terms of speed as well as memory: + * - No closures, instead use prototypical inheritance for API + * - Internal state needs to be stored on scope directly, which means that private state is + * exposed as $$____ properties + * + * Loop operations are optimized by using while(count--) { ... } + * - this means that in order to keep the same order of execution as addition we have to add + * items to the array at the beginning (shift) instead of at the end (push) + * + * Child scopes are created and removed often + * - Using an array would be slow since inserts in middle are expensive so we use linked list + * + * There are few watches then a lot of observers. This is why you don't want the observer to be + * implemented in the same way as watch. Watch requires return of initialization function which + * are expensive to construct. + */ + + +/** + * @ngdoc object + * @name ng.$rootScopeProvider + * @description + * + * Provider for the $rootScope service. + */ + +/** + * @ngdoc function + * @name ng.$rootScopeProvider#digestTtl + * @methodOf ng.$rootScopeProvider + * @description + * + * Sets the number of digest iterations the scope should attempt to execute before giving up and + * assuming that the model is unstable. + * + * The current default is 10 iterations. + * + * @param {number} limit The number of digest iterations. + */ + + +/** + * @ngdoc object + * @name ng.$rootScope + * @description + * + * Every application has a single root {@link ng.$rootScope.Scope scope}. + * All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide + * event processing life-cycle. See {@link guide/scope developer guide on scopes}. + */ +function $RootScopeProvider(){ + var TTL = 10; + var $rootScopeMinErr = minErr('$rootScope'); + + this.digestTtl = function(value) { + if (arguments.length) { + TTL = value; + } + return TTL; + }; + + this.$get = ['$injector', '$exceptionHandler', '$parse', + function( $injector, $exceptionHandler, $parse) { + + /** + * @ngdoc function + * @name ng.$rootScope.Scope * - * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx - * JSON vulnerability} allows third party website to turn your JSON resource URL into - * {@link http://en.wikipedia.org/wiki/JSONP JSONP} request under some conditions. To - * counter this your server can prefix all JSON requests with following string `")]}',\n"`. - * Angular will automatically strip the prefix before processing it as JSON. + * @description + * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the + * {@link AUTO.$injector $injector}. Child scopes are created using the + * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when + * compiled HTML template is executed.) * - * For example if your server needs to return: + * Here is a simple scope snippet to show how you can interact with the scope. *
-     * ['one','two']
+     * 
      * 
* - * which is vulnerable to attack, your server can return: + * # Inheritance + * A scope can inherit from a parent scope, as in this example: *
-     * )]}',
-     * ['one','two']
-     * 
- * - * Angular will strip the prefix, before processing the JSON. - * - * - * ## Cross Site Request Forgery (XSRF) Protection - * - * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which - * an unauthorized site can gain your user's private data. Angular provides a mechanism - * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie - * called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that - * runs on your domain could read the cookie, your server can be assured that the XHR came from - * JavaScript running on your domain. - * - * To take advantage of this, your server needs to set a token in a JavaScript readable session - * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the - * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure - * that only JavaScript running on your domain could have sent the request. The token must be - * unique for each user and must be verifiable by the server (to prevent the JavaScript from making - * up its own tokens). We recommend that the token is a digest of your site's authentication - * cookie with a {@link https://en.wikipedia.org/wiki/Salt_(cryptography) salt} for added security. - * - * - * @param {object} config Object describing the request to be made and how it should be - * processed. The object has following properties: - * - * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) - * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. - * - **params** – `{Object.}` – Map of strings or objects which will be turned to - * `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified. - * - **data** – `{string|Object}` – Data to be sent as the request message data. - * - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server. - * - **transformRequest** – `{function(data, headersGetter)|Array.}` – - * transform function or an array of such functions. The transform function takes the http - * request body and headers and returns its transformed (typically serialized) version. - * - **transformResponse** – `{function(data, headersGetter)|Array.}` – - * transform function or an array of such functions. The transform function takes the http - * response body and headers and returns its transformed (typically deserialized) version. - * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the - * GET request, otherwise if a cache instance built with - * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for - * caching. - * - **timeout** – `{number}` – timeout in milliseconds. - * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the - * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 - * requests with credentials} for more information. - * - * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the - * standard `then` method and two http specific methods: `success` and `error`. The `then` - * method takes two arguments a success and an error callback which will be called with a - * response object. The `success` and `error` methods take a single argument - a function that - * will be called when the request succeeds or fails respectively. The arguments passed into - * these functions are destructured representation of the response object passed into the - * `then` method. The response object has these properties: - * - * - **data** – `{string|Object}` – The response body transformed with the transform functions. - * - **status** – `{number}` – HTTP status code of the response. - * - **headers** – `{function([headerName])}` – Header getter function. - * - **config** – `{Object}` – The configuration object that was used to generate the request. - * - * @property {Array.} pendingRequests Array of config objects for currently pending - * requests. This is primarily meant to be used for debugging purposes. - * - * - * @example - - -
- - -
- - - -
http status code: {{status}}
-
http response data: {{data}}
-
-
- - function FetchCtrl($scope, $http, $templateCache) { - $scope.method = 'GET'; - $scope.url = 'http-hello.html'; + var parent = $rootScope; + var child = parent.$new(); + + parent.salutation = "Hello"; + child.name = "World"; + expect(child.salutation).toEqual('Hello'); + + child.salutation = "Welcome"; + expect(child.salutation).toEqual('Welcome'); + expect(parent.salutation).toEqual('Hello'); + * + * + * + * @param {Object.=} providers Map of service factory which need to be provided + * for the current scope. Defaults to {@link ng}. + * @param {Object.=} instanceCache Provides pre-instantiated services which should + * append/override services provided by `providers`. This is handy when unit-testing and having + * the need to override a default service. + * @returns {Object} Newly created scope. + * + */ + function Scope() { + this.$id = nextUid(); + this.$$phase = this.$parent = this.$$watchers = + this.$$nextSibling = this.$$prevSibling = + this.$$childHead = this.$$childTail = null; + this['this'] = this.$root = this; + this.$$destroyed = false; + this.$$asyncQueue = []; + this.$$listeners = {}; + this.$$isolateBindings = {}; + } + + /** + * @ngdoc property + * @name ng.$rootScope.Scope#$id + * @propertyOf ng.$rootScope.Scope + * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for + * debugging. + */ + + + Scope.prototype = { + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$new + * @methodOf ng.$rootScope.Scope + * @function + * + * @description + * Creates a new child {@link ng.$rootScope.Scope scope}. + * + * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and + * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope + * hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. + * + * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for + * the scope and its child scopes to be permanently detached from the parent and thus stop + * participating in model change detection and listener notification by invoking. + * + * @param {boolean} isolate if true then the scope does not prototypically inherit from the + * parent scope. The scope is isolated, as it can not see parent scope properties. + * When creating widgets it is useful for the widget to not accidentally read parent + * state. + * + * @returns {Object} The newly created child scope. + * + */ + $new: function(isolate) { + var Child, + child; + + if (isolate) { + child = new Scope(); + child.$root = this.$root; + // ensure that there is just one async queue per $rootScope and it's children + child.$$asyncQueue = this.$$asyncQueue; + } else { + Child = function() {}; // should be anonymous; This is so that when the minifier munges + // the name it does not become random set of chars. These will then show up as class + // name in the debugger. + Child.prototype = this; + child = new Child(); + child.$id = nextUid(); + } + child['this'] = child; + child.$$listeners = {}; + child.$parent = this; + child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; + child.$$prevSibling = this.$$childTail; + if (this.$$childHead) { + this.$$childTail.$$nextSibling = child; + this.$$childTail = child; + } else { + this.$$childHead = this.$$childTail = child; + } + return child; + }, + + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$watch + * @methodOf ng.$rootScope.Scope + * @function + * + * @description + * Registers a `listener` callback to be executed whenever the `watchExpression` changes. + * + * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and + * should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()} + * reruns when it detects changes the `watchExpression` can execute multiple times per + * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) + * - The `listener` is called only when the value from the current `watchExpression` and the + * previous call to `watchExpression` are not equal (with the exception of the initial run, + * see below). The inequality is determined according to + * {@link angular.equals} function. To save the value of the object for later comparison, the + * {@link angular.copy} function is used. It also means that watching complex options will + * have adverse memory and performance implications. + * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This + * is achieved by rerunning the watchers until no changes are detected. The rerun iteration + * limit is 10 to prevent an infinite loop deadlock. + * + * + * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, + * you can register a `watchExpression` function with no `listener`. (Since `watchExpression` + * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is + * detected, be prepared for multiple calls to your listener.) + * + * After a watcher is registered with the scope, the `listener` fn is called asynchronously + * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the + * watcher. In rare cases, this is undesirable because the listener is called when the result + * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you + * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the + * listener was called due to initialization. + * + * + * # Example + *
+           // let's assume that scope was dependency injected as the $rootScope
+           var scope = $rootScope;
+           scope.name = 'misko';
+           scope.counter = 0;
+
+           expect(scope.counter).toEqual(0);
+           scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; });
+           expect(scope.counter).toEqual(0);
+
+           scope.$digest();
+           // no variable change
+           expect(scope.counter).toEqual(0);
+
+           scope.name = 'adam';
+           scope.$digest();
+           expect(scope.counter).toEqual(1);
+       * 
+ * + * + * + * @param {(function()|string)} watchExpression Expression that is evaluated on each + * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a + * call to the `listener`. + * + * - `string`: Evaluated as {@link guide/expression expression} + * - `function(scope)`: called with current `scope` as a parameter. + * @param {(function()|string)=} listener Callback called whenever the return value of + * the `watchExpression` changes. + * + * - `string`: Evaluated as {@link guide/expression expression} + * - `function(newValue, oldValue, scope)`: called with current and previous values as parameters. + * + * @param {boolean=} objectEquality Compare object for equality rather than for reference. + * @returns {function()} Returns a deregistration function for this listener. + */ + $watch: function(watchExp, listener, objectEquality) { + var scope = this, + get = compileToFn(watchExp, 'watch'), + array = scope.$$watchers, + watcher = { + fn: listener, + last: initWatchVal, + get: get, + exp: watchExp, + eq: !!objectEquality + }; + + // in the case user pass string, we need to compile it, do we really need this ? + if (!isFunction(listener)) { + var listenFn = compileToFn(listener || noop, 'listener'); + watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; + } + + if (typeof watchExp == 'string' && get.constant) { + var originalFn = watcher.fn; + watcher.fn = function(newVal, oldVal, scope) { + originalFn.call(this, newVal, oldVal, scope); + arrayRemove(array, watcher); + }; + } + + if (!array) { + array = scope.$$watchers = []; + } + // we use unshift since we use a while loop in $digest for speed. + // the while loop reads in reverse order. + array.unshift(watcher); + + return function() { + arrayRemove(array, watcher); + }; + }, + + + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$watchCollection + * @methodOf ng.$rootScope.Scope + * @function + * + * @description + * Shallow watches the properties of an object and fires whenever any of the properties change + * (for arrays this implies watching the array items, for object maps this implies watching the properties). + * If a change is detected the `listener` callback is fired. + * + * - The `obj` collection is observed via standard $watch operation and is examined on every call to $digest() to + * see if any items have been added, removed, or moved. + * - The `listener` is called whenever anything within the `obj` has changed. Examples include adding new items + * into the object or array, removing and moving items around. + * + * + * # Example + *
+          $scope.names = ['igor', 'matias', 'misko', 'james'];
+          $scope.dataCount = 4;
+
+          $scope.$watchCollection('names', function(newNames, oldNames) {
+            $scope.dataCount = newNames.length;
+          });
+
+          expect($scope.dataCount).toEqual(4);
+          $scope.$digest();
+
+          //still at 4 ... no changes
+          expect($scope.dataCount).toEqual(4);
+
+          $scope.names.pop();
+          $scope.$digest();
+
+          //now there's been a change
+          expect($scope.dataCount).toEqual(3);
+       * 
+ * + * + * @param {string|Function(scope)} obj Evaluated as {@link guide/expression expression}. The expression value + * should evaluate to an object or an array which is observed on each + * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the collection will trigger + * a call to the `listener`. + * + * @param {function(newCollection, oldCollection, scope)} listener a callback function that is fired with both + * the `newCollection` and `oldCollection` as parameters. + * The `newCollection` object is the newly modified data obtained from the `obj` expression and the + * `oldCollection` object is a copy of the former collection data. + * The `scope` refers to the current scope. + * + * @returns {function()} Returns a de-registration function for this listener. When the de-registration function is executed + * then the internal watch operation is terminated. + */ + $watchCollection: function(obj, listener) { + var self = this; + var oldValue; + var newValue; + var changeDetected = 0; + var objGetter = $parse(obj); + var internalArray = []; + var internalObject = {}; + var oldLength = 0; + + function $watchCollectionWatch() { + newValue = objGetter(self); + var newLength, key; + + if (!isObject(newValue)) { + if (oldValue !== newValue) { + oldValue = newValue; + changeDetected++; + } + } else if (isArrayLike(newValue)) { + if (oldValue !== internalArray) { + // we are transitioning from something which was not an array into array. + oldValue = internalArray; + oldLength = oldValue.length = 0; + changeDetected++; + } + + newLength = newValue.length; + + if (oldLength !== newLength) { + // if lengths do not match we need to trigger change notification + changeDetected++; + oldValue.length = oldLength = newLength; + } + // copy the items to oldValue and look for changes. + for (var i = 0; i < newLength; i++) { + if (oldValue[i] !== newValue[i]) { + changeDetected++; + oldValue[i] = newValue[i]; + } + } + } else { + if (oldValue !== internalObject) { + // we are transitioning from something which was not an object into object. + oldValue = internalObject = {}; + oldLength = 0; + changeDetected++; + } + // copy the items to oldValue and look for changes. + newLength = 0; + for (key in newValue) { + if (newValue.hasOwnProperty(key)) { + newLength++; + if (oldValue.hasOwnProperty(key)) { + if (oldValue[key] !== newValue[key]) { + changeDetected++; + oldValue[key] = newValue[key]; + } + } else { + oldLength++; + oldValue[key] = newValue[key]; + changeDetected++; + } + } + } + if (oldLength > newLength) { + // we used to have more keys, need to find them and destroy them. + changeDetected++; + for(key in oldValue) { + if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) { + oldLength--; + delete oldValue[key]; + } + } + } + } + return changeDetected; + } + + function $watchCollectionAction() { + listener(newValue, oldValue, self); + } + + return this.$watch($watchCollectionWatch, $watchCollectionAction); + }, + + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$digest + * @methodOf ng.$rootScope.Scope + * @function + * + * @description + * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children. + * Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the + * `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are + * firing. This means that it is possible to get into an infinite loop. This function will throw + * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10. + * + * Usually you don't call `$digest()` directly in + * {@link ng.directive:ngController controllers} or in + * {@link ng.$compileProvider#directive directives}. + * Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a + * {@link ng.$compileProvider#directive directives}) will force a `$digest()`. + * + * If you want to be notified whenever `$digest()` is called, + * you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()} + * with no `listener`. + * + * You may have a need to call `$digest()` from within unit-tests, to simulate the scope + * life-cycle. + * + * # Example + *
+           var scope = ...;
+           scope.name = 'misko';
+           scope.counter = 0;
 
-            $scope.fetch = function() {
-              $scope.code = null;
-              $scope.response = null;
+           expect(scope.counter).toEqual(0);
+           scope.$watch('name', function(newValue, oldValue) {
+             scope.counter = scope.counter + 1;
+           });
+           expect(scope.counter).toEqual(0);
 
-              $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
-                success(function(data, status) {
-                  $scope.status = status;
-                  $scope.data = data;
-                }).
-                error(function(data, status) {
-                  $scope.data = data || "Request failed";
-                  $scope.status = status;
-              });
-            };
+           scope.$digest();
+           // no variable change
+           expect(scope.counter).toEqual(0);
 
-            $scope.updateModel = function(method, url) {
-              $scope.method = method;
-              $scope.url = url;
-            };
+           scope.name = 'adam';
+           scope.$digest();
+           expect(scope.counter).toEqual(1);
+       * 
+ * + */ + $digest: function() { + var watch, value, last, + watchers, + asyncQueue = this.$$asyncQueue, + length, + dirty, ttl = TTL, + next, current, target = this, + watchLog = [], + logIdx, logMsg; + + beginPhase('$digest'); + + do { // "while dirty" loop + dirty = false; + current = target; + + while(asyncQueue.length) { + try { + current.$eval(asyncQueue.shift()); + } catch (e) { + $exceptionHandler(e); + } + } + + do { // "traverse the scopes" loop + if ((watchers = current.$$watchers)) { + // process our watches + length = watchers.length; + while (length--) { + try { + watch = watchers[length]; + // Most common watches are on primitives, in which case we can short + // circuit it with === operator, only when === fails do we use .equals + if (watch && (value = watch.get(current)) !== (last = watch.last) && + !(watch.eq + ? equals(value, last) + : (typeof value == 'number' && typeof last == 'number' + && isNaN(value) && isNaN(last)))) { + dirty = true; + watch.last = watch.eq ? copy(value) : value; + watch.fn(value, ((last === initWatchVal) ? value : last), current); + if (ttl < 5) { + logIdx = 4 - ttl; + if (!watchLog[logIdx]) watchLog[logIdx] = []; + logMsg = (isFunction(watch.exp)) + ? 'fn: ' + (watch.exp.name || watch.exp.toString()) + : watch.exp; + logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); + watchLog[logIdx].push(logMsg); + } + } + } catch (e) { + $exceptionHandler(e); + } + } + } + + // Insanity Warning: scope depth-first traversal + // yes, this code is a bit crazy, but it works and we have tests to prove it! + // this piece should be kept in sync with the traversal in $broadcast + if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { + while(current !== target && !(next = current.$$nextSibling)) { + current = current.$parent; + } + } + } while ((current = next)); + + if(dirty && !(ttl--)) { + clearPhase(); + throw $rootScopeMinErr('infdig', + '{0} $digest() iterations reached. Aborting!\nWatchers fired in the last 5 iterations: {1}', + TTL, toJson(watchLog)); + } + } while (dirty || asyncQueue.length); + + clearPhase(); + }, + + + /** + * @ngdoc event + * @name ng.$rootScope.Scope#$destroy + * @eventOf ng.$rootScope.Scope + * @eventType broadcast on scope being destroyed + * + * @description + * Broadcasted when a scope and its children are being destroyed. + * + * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to + * clean up DOM bindings before an element is removed from the DOM. + */ + + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$destroy + * @methodOf ng.$rootScope.Scope + * @function + * + * @description + * Removes the current scope (and all of its children) from the parent scope. Removal implies + * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer + * propagate to the current scope and its children. Removal also implies that the current + * scope is eligible for garbage collection. + * + * The `$destroy()` is usually used by directives such as + * {@link ng.directive:ngRepeat ngRepeat} for managing the + * unrolling of the loop. + * + * Just before a scope is destroyed a `$destroy` event is broadcasted on this scope. + * Application code can register a `$destroy` event handler that will give it chance to + * perform any necessary cleanup. + * + * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to + * clean up DOM bindings before an element is removed from the DOM. + */ + $destroy: function() { + // we can't destroy the root scope or a scope that has been already destroyed + if ($rootScope == this || this.$$destroyed) return; + var parent = this.$parent; + + this.$broadcast('$destroy'); + this.$$destroyed = true; + + if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; + if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; + if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; + if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; + + // This is bogus code that works around Chrome's GC leak + // see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 + this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = + this.$$childTail = null; + }, + + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$eval + * @methodOf ng.$rootScope.Scope + * @function + * + * @description + * Executes the `expression` on the current scope returning the result. Any exceptions in the + * expression are propagated (uncaught). This is useful when evaluating Angular expressions. + * + * # Example + *
+           var scope = ng.$rootScope.Scope();
+           scope.a = 1;
+           scope.b = 2;
+
+           expect(scope.$eval('a+b')).toEqual(3);
+           expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
+       * 
+ * + * @param {(string|function())=} expression An angular expression to be executed. + * + * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `function(scope)`: execute the function with the current `scope` parameter. + * + * @returns {*} The result of evaluating the expression. + */ + $eval: function(expr, locals) { + return $parse(expr)(this, locals); + }, + + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$evalAsync + * @methodOf ng.$rootScope.Scope + * @function + * + * @description + * Executes the expression on the current scope at a later point in time. + * + * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that: + * + * - it will execute in the current script execution context (before any DOM rendering). + * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after + * `expression` execution. + * + * Any exceptions from the execution of the expression are forwarded to the + * {@link ng.$exceptionHandler $exceptionHandler} service. + * + * @param {(string|function())=} expression An angular expression to be executed. + * + * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `function(scope)`: execute the function with the current `scope` parameter. + * + */ + $evalAsync: function(expr) { + this.$$asyncQueue.push(expr); + }, + + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$apply + * @methodOf ng.$rootScope.Scope + * @function + * + * @description + * `$apply()` is used to execute an expression in angular from outside of the angular framework. + * (For example from browser DOM events, setTimeout, XHR or third party libraries). + * Because we are calling into the angular framework we need to perform proper scope life-cycle + * of {@link ng.$exceptionHandler exception handling}, + * {@link ng.$rootScope.Scope#$digest executing watches}. + * + * ## Life cycle + * + * # Pseudo-Code of `$apply()` + *
+           function $apply(expr) {
+             try {
+               return $eval(expr);
+             } catch (e) {
+               $exceptionHandler(e);
+             } finally {
+               $root.$digest();
+             }
+           }
+       * 
+ * + * + * Scope's `$apply()` method transitions through the following stages: + * + * 1. The {@link guide/expression expression} is executed using the + * {@link ng.$rootScope.Scope#$eval $eval()} method. + * 2. Any exceptions from the execution of the expression are forwarded to the + * {@link ng.$exceptionHandler $exceptionHandler} service. + * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression + * was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. + * + * + * @param {(string|function())=} exp An angular expression to be executed. + * + * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `function(scope)`: execute the function with current `scope` parameter. + * + * @returns {*} The result of evaluating the expression. + */ + $apply: function(expr) { + try { + beginPhase('$apply'); + return this.$eval(expr); + } catch (e) { + $exceptionHandler(e); + } finally { + clearPhase(); + try { + $rootScope.$digest(); + } catch (e) { + $exceptionHandler(e); + throw e; } -
- - Hello, $http! - - - it('should make an xhr GET request', function() { - element(':button:contains("Sample GET")').click(); - element(':button:contains("fetch")').click(); - expect(binding('status')).toBe('200'); - expect(binding('data')).toMatch(/Hello, \$http!/); - }); + } + }, - it('should make a JSONP request to angularjs.org', function() { - element(':button:contains("Sample JSONP")').click(); - element(':button:contains("fetch")').click(); - expect(binding('status')).toBe('200'); - expect(binding('data')).toMatch(/Super Hero!/); - }); + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$on + * @methodOf ng.$rootScope.Scope + * @function + * + * @description + * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of + * event life cycle. + * + * The event listener function format is: `function(event, args...)`. The `event` object + * passed into the listener has the following attributes: + * + * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or `$broadcast`-ed. + * - `currentScope` - `{Scope}`: the current scope which is handling the event. + * - `name` - `{string}`: Name of the event. + * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel further event + * propagation (available only for events that were `$emit`-ed). + * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag to true. + * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. + * + * @param {string} name Event name to listen on. + * @param {function(event, args...)} listener Function to call when the event is emitted. + * @returns {function()} Returns a deregistration function for this listener. + */ + $on: function(name, listener) { + var namedListeners = this.$$listeners[name]; + if (!namedListeners) { + this.$$listeners[name] = namedListeners = []; + } + namedListeners.push(listener); - it('should make JSONP request to invalid URL and invoke the error handler', - function() { - element(':button:contains("Invalid JSONP")').click(); - element(':button:contains("fetch")').click(); - expect(binding('status')).toBe('0'); - expect(binding('data')).toBe('Request failed'); - }); - -
- */ - function $http(config) { - config.method = uppercase(config.method); + return function() { + namedListeners[indexOf(namedListeners, listener)] = null; + }; + }, - var reqTransformFn = config.transformRequest || $config.transformRequest, - respTransformFn = config.transformResponse || $config.transformResponse, - defHeaders = $config.headers, - reqHeaders = extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']}, - defHeaders.common, defHeaders[lowercase(config.method)], config.headers), - reqData = transformData(config.data, headersGetter(reqHeaders), reqTransformFn), - promise; - // strip content-type if data is undefined - if (isUndefined(config.data)) { - delete reqHeaders['Content-Type']; - } + /** + * @ngdoc function + * @name ng.$rootScope.Scope#$emit + * @methodOf ng.$rootScope.Scope + * @function + * + * @description + * Dispatches an event `name` upwards through the scope hierarchy notifying the + * registered {@link ng.$rootScope.Scope#$on} listeners. + * + * The event life cycle starts at the scope on which `$emit` was called. All + * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. + * Afterwards, the event traverses upwards toward the root scope and calls all registered + * listeners along the way. The event will stop propagating if one of the listeners cancels it. + * + * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed + * onto the {@link ng.$exceptionHandler $exceptionHandler} service. + * + * @param {string} name Event name to emit. + * @param {...*} args Optional set of arguments which will be passed onto the event listeners. + * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} + */ + $emit: function(name, args) { + var empty = [], + namedListeners, + scope = this, + stopPropagation = false, + event = { + name: name, + targetScope: scope, + stopPropagation: function() {stopPropagation = true;}, + preventDefault: function() { + event.defaultPrevented = true; + }, + defaultPrevented: false + }, + listenerArgs = concat([event], arguments, 1), + i, length; - // send request - promise = sendReq(config, reqData, reqHeaders); + do { + namedListeners = scope.$$listeners[name] || empty; + event.currentScope = scope; + for (i=0, length=namedListeners.length; i to learn more about them. + * You can ensure your document is in standards mode and not quirks mode by adding `` + * to the top of your HTML document. + * + * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for + * security vulnerabilities such as XSS, clickjacking, etc. a lot easier. + * + * Here's an example of a binding in a privileged context: + * + *
+ *     
+ *     
+ *
+ * + * Notice that `ng-bind-html` is bound to `{{userHtml}}` controlled by the user. With SCE + * disabled, this application allows the user to render arbitrary HTML into the DIV. + * In a more realistic example, one may be rendering user comments, blog articles, etc. via + * bindings. (HTML is just one example of a context where rendering user controlled input creates + * security vulnerabilities.) + * + * For the case of HTML, you might use a library, either on the client side, or on the server side, + * to sanitize unsafe HTML before binding to the value and rendering it in the document. + * + * How would you ensure that every place that used these types of bindings was bound to a value that + * was sanitized by your library (or returned as safe for rendering by your server?) How can you + * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some + * properties/fields and forgot to update the binding to the sanitized value? + * + * To be secure by default, you want to ensure that any such bindings are disallowed unless you can + * determine that something explicitly says it's safe to use a value for binding in that + * context. You can then audit your code (a simple grep would do) to ensure that this is only done + * for those values that you can easily tell are safe - because they were received from your server, + * sanitized by your library, etc. You can organize your codebase to help with this - perhaps + * allowing only the files in a specific directory to do this. Ensuring that the internal API + * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task. + * + * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs} (and shorthand + * methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to obtain values that will be + * accepted by SCE / privileged contexts. + * + * + * ## How does it work? + * + * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted + * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link + * ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the + * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. + * + * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link + * ng.$sce#parseHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly + * simplified): + * + *
+ *   var ngBindHtmlDirective = ['$sce', function($sce) {
+ *     return function(scope, element, attr) {
+ *       scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
+ *         element.html(value || '');
+ *       });
+ *     };
+ *   }];
+ * 
+ * + * ## Impact on loading templates + * + * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as + * `templateUrl`'s specified by {@link guide/directive directives}. + * + * By default, Angular only loads templates from the same domain and protocol as the application + * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl + * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or + * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist + * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. + * + * *Please note*: + * The browser's + * {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest + * Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing (CORS)} + * policy apply in addition to this and may further restrict whether the template is successfully + * loaded. This means that without the right CORS policy, loading templates from a different domain + * won't work on all browsers. Also, loading templates from `file://` URL does not work on some + * browsers. + * + * ## This feels like too much overhead for the developer? + * + * It's important to remember that SCE only applies to interpolation expressions. + * + * If your expressions are constant literals, they're automatically trusted and you don't need to + * call `$sce.trustAs` on them. (e.g. + * `
`) just works. + * + * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them + * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here. + * + * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load + * templates in `ng-include` from your application's domain without having to even know about SCE. + * It blocks loading templates from other domains or loading templates over http from an https + * served document. You can change these by setting your own custom {@link + * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link + * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs. + * + * This significantly reduces the overhead. It is far easier to pay the small overhead and have an + * application that's secure and can be audited to verify that with much more ease than bolting + * security onto an application later. + * + * ## What trusted context types are supported? + * + * | Context | Notes | + * |=====================|================| + * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. | + * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. | + * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`
Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. | + * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. | + * + * ## Show me an example. + * + * + * + * @example + + +
+

+ User comments
+ By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when $sanitize is available. If $sanitize isn't available, this results in an error instead of an exploit. +
+
+ {{userComment.name}}: + +
+
+
+
+
- if (lowercase(method) == 'jsonp') { - var callbackId = '_' + (callbacks.counter++).toString(36); - callbacks[callbackId] = function(data) { - callbacks[callbackId].data = data; - }; + + var mySceApp = angular.module('mySceApp', ['ngSanitize']); - jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), - function() { - if (callbacks[callbackId].data) { - completeRequest(callback, 200, callbacks[callbackId].data); - } else { - completeRequest(callback, -2); - } - delete callbacks[callbackId]; + mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) { + var self = this; + $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) { + self.userComments = userComments; }); - } else { - var xhr = new XHR(); - xhr.open(method, url, true); - forEach(headers, function(value, key) { - if (value) xhr.setRequestHeader(key, value); + self.explicitlyTrustedHtml = $sce.trustAsHtml( + 'Hover over this text.'); + }); + + + + [ + { "name": "Alice", + "htmlComment": "Is anyone reading this?" + }, + { "name": "Bob", + "htmlComment": "Yes! Am I the only other one?" + } + ] + + + + describe('SCE doc demo', function() { + it('should sanitize untrusted values', function() { + expect(element('.htmlComment').html()).toBe('Is anyone reading this?'); }); + it('should NOT sanitize explicitly trusted values', function() { + expect(element('#explicitlyTrustedHtml').html()).toBe( + 'Hover over this text.'); + }); + }); + +
+ * + * + * + * ## Can I disable SCE completely? + * + * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits + * for little coding overhead. It will be much harder to take an SCE disabled application and + * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE + * for cases where you have a lot of existing code that was written before SCE was introduced and + * you're migrating them a module at a time. + * + * That said, here's how you can completely disable SCE: + * + *
+ *   angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
+ *     // Completely disable SCE.  For demonstration purposes only!
+ *     // Do not use in new projects.
+ *     $sceProvider.enabled(false);
+ *   });
+ * 
+ * + */ - var status; +function $SceProvider() { + var enabled = true; - // In IE6 and 7, this might be called synchronously when xhr.send below is called and the - // response is in the cache. the promise api will ensure that to the app code the api is - // always async - xhr.onreadystatechange = function() { - if (xhr.readyState == 4) { - var responseHeaders = xhr.getAllResponseHeaders(); + /** + * @ngdoc function + * @name ng.sceProvider#enabled + * @methodOf ng.$sceProvider + * @function + * + * @param {boolean=} value If provided, then enables/disables SCE. + * @return {boolean} true if SCE is enabled, false otherwise. + * + * @description + * Enables/disables SCE and returns the current value. + */ + this.enabled = function (value) { + if (arguments.length) { + enabled = !!value; + } + return enabled; + }; - // TODO(vojta): remove once Firefox 21 gets released. - // begin: workaround to overcome Firefox CORS http response headers bug - // https://bugzilla.mozilla.org/show_bug.cgi?id=608735 - // Firefox already patched in nightly. Should land in Firefox 21. - // CORS "simple response headers" http://www.w3.org/TR/cors/ - var value, - simpleHeaders = ["Cache-Control", "Content-Language", "Content-Type", - "Expires", "Last-Modified", "Pragma"]; - if (!responseHeaders) { - responseHeaders = ""; - forEach(simpleHeaders, function (header) { - var value = xhr.getResponseHeader(header); - if (value) { - responseHeaders += header + ": " + value + "\n"; - } - }); - } - // end of the workaround. + /* Design notes on the default implementation for SCE. + * + * The API contract for the SCE delegate + * ------------------------------------- + * The SCE delegate object must provide the following 3 methods: + * + * - trustAs(contextEnum, value) + * This method is used to tell the SCE service that the provided value is OK to use in the + * contexts specified by contextEnum. It must return an object that will be accepted by + * getTrusted() for a compatible contextEnum and return this value. + * + * - valueOf(value) + * For values that were not produced by trustAs(), return them as is. For values that were + * produced by trustAs(), return the corresponding input value to trustAs. Basically, if + * trustAs is wrapping the given values into some type, this operation unwraps it when given + * such a value. + * + * - getTrusted(contextEnum, value) + * This function should return the a value that is safe to use in the context specified by + * contextEnum or throw and exception otherwise. + * + * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be opaque + * or wrapped in some holder object. That happens to be an implementation detail. For instance, + * an implementation could maintain a registry of all trusted objects by context. In such a case, + * trustAs() would return the same object that was passed in. getTrusted() would return the same + * object passed in if it was found in the registry under a compatible context or throw an + * exception otherwise. An implementation might only wrap values some of the time based on + * some criteria. getTrusted() might return a value and not throw an exception for special + * constants or objects even if not wrapped. All such implementations fulfill this contract. + * + * + * A note on the inheritance model for SCE contexts + * ------------------------------------------------ + * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This + * is purely an implementation details. + * + * The contract is simply this: + * + * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value) + * will also succeed. + * + * Inheritance happens to capture this in a natural way. In some future, we + * may not use inheritance anymore. That is OK because no code outside of + * sce.js and sceSpecs.js would need to be aware of this detail. + */ + + this.$get = ['$parse', '$document', '$sceDelegate', function( + $parse, $document, $sceDelegate) { + // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows + // the "expression(javascript expression)" syntax which is insecure. + if (enabled && msie) { + var documentMode = $document[0].documentMode; + if (documentMode !== undefined && documentMode < 8) { + throw $sceMinErr('iequirks', + 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' + + 'mode. You can fix this by adding the text to the top of your HTML ' + + 'document. See http://docs.angularjs.org/api/ng.$sce for more information.'); + } + } + + var sce = copy(SCE_CONTEXTS); + + /** + * @ngdoc function + * @name ng.sce#isEnabled + * @methodOf ng.$sce + * @function + * + * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you + * have to do it at module config time on {@link ng.$sceProvider $sceProvider}. + * + * @description + * Returns a boolean indicating if SCE is enabled. + */ + sce.isEnabled = function () { + return enabled; + }; + sce.trustAs = $sceDelegate.trustAs; + sce.getTrusted = $sceDelegate.getTrusted; + sce.valueOf = $sceDelegate.valueOf; + + if (!enabled) { + sce.trustAs = sce.getTrusted = function(type, value) { return value; }, + sce.valueOf = identity + } + + /** + * @ngdoc method + * @name ng.$sce#parse + * @methodOf ng.$sce + * + * @description + * Converts Angular {@link guide/expression expression} into a function. This is like {@link + * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it + * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*, + * *result*)} + * + * @param {string} type The kind of SCE context in which this result will be used. + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ + sce.parseAs = function sceParseAs(type, expr) { + var parsed = $parse(expr); + if (parsed.literal && parsed.constant) { + return parsed; + } else { + return function sceParseAsTrusted(self, locals) { + return sce.getTrusted(type, parsed(self, locals)); + } + } + }; + + /** + * @ngdoc method + * @name ng.$sce#trustAs + * @methodOf ng.$sce + * + * @description + * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, returns an object + * that is trusted by angular for use in specified strict contextual escaping contexts (such as + * ng-html-bind-unsafe, ng-include, any src attribute interpolation, any dom event binding + * attribute interpolation such as for onclick, etc.) that uses the provided value. See * + * {@link ng.$sce $sce} for enabling strict contextual escaping. + * + * @param {string} type The kind of context in which this value is safe for use. e.g. url, + * resource_url, html, js and css. + * @param {*} value The value that that should be considered trusted/safe. + * @returns {*} A value that can be used to stand in for the provided `value` in places + * where Angular expects a $sce.trustAs() return value. + */ + + /** + * @ngdoc method + * @name ng.$sce#trustAsHtml + * @methodOf ng.$sce + * + * @description + * Shorthand method. `$sce.trustAsHtml(value)` → {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`} + * + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml + * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the + * return value of {@link ng.$sce#trustAs $sce.trustAs}.) + */ + + /** + * @ngdoc method + * @name ng.$sce#trustAsUrl + * @methodOf ng.$sce + * + * @description + * Shorthand method. `$sce.trustAsUrl(value)` → {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`} + * + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl + * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the + * return value of {@link ng.$sce#trustAs $sce.trustAs}.) + */ + + /** + * @ngdoc method + * @name ng.$sce#trustAsResourceUrl + * @methodOf ng.$sce + * + * @description + * Shorthand method. `$sce.trustAsResourceUrl(value)` → {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} + * + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl + * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the return + * value of {@link ng.$sce#trustAs $sce.trustAs}.) + */ + + /** + * @ngdoc method + * @name ng.$sce#trustAsJs + * @methodOf ng.$sce + * + * @description + * Shorthand method. `$sce.trustAsJs(value)` → {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`} + * + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs + * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the + * return value of {@link ng.$sce#trustAs $sce.trustAs}.) + */ - completeRequest(callback, status || xhr.status, xhr.responseText, - responseHeaders); - } - }; + /** + * @ngdoc method + * @name ng.$sce#getTrusted + * @methodOf ng.$sce + * + * @description + * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, takes + * the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the originally supplied + * value if the queried context type is a supertype of the created type. If this condition + * isn't satisfied, throws an exception. + * + * @param {string} type The kind of context in which this value is to be used. + * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`} call. + * @returns {*} The value the was originally provided to {@link ng.$sce#trustAs `$sce.trustAs`} if + * valid in this context. Otherwise, throws an exception. + */ - if (withCredentials) { - xhr.withCredentials = true; - } + /** + * @ngdoc method + * @name ng.$sce#getTrustedHtml + * @methodOf ng.$sce + * + * @description + * Shorthand method. `$sce.getTrustedHtml(value)` → {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)` + */ - xhr.send(post || ''); + /** + * @ngdoc method + * @name ng.$sce#getTrustedCss + * @methodOf ng.$sce + * + * @description + * Shorthand method. `$sce.getTrustedCss(value)` → {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)` + */ - if (timeout > 0) { - $browserDefer(function() { - status = -1; - xhr.abort(); - }, timeout); - } - } + /** + * @ngdoc method + * @name ng.$sce#getTrustedUrl + * @methodOf ng.$sce + * + * @description + * Shorthand method. `$sce.getTrustedUrl(value)` → {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)` + */ + /** + * @ngdoc method + * @name ng.$sce#getTrustedResourceUrl + * @methodOf ng.$sce + * + * @description + * Shorthand method. `$sce.getTrustedResourceUrl(value)` → {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} + * + * @param {*} value The value to pass to `$sceDelegate.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` + */ - function completeRequest(callback, status, response, headersString) { - // URL_MATCH is defined in src/service/location.js - var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[1]; + /** + * @ngdoc method + * @name ng.$sce#getTrustedJs + * @methodOf ng.$sce + * + * @description + * Shorthand method. `$sce.getTrustedJs(value)` → {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)` + */ - // fix status code for file protocol (it's always 0) - status = (protocol == 'file') ? (response ? 200 : 404) : status; + /** + * @ngdoc method + * @name ng.$sce#parseAsHtml + * @methodOf ng.$sce + * + * @description + * Shorthand method. `$sce.parseAsHtml(expression string)` → {@link ng.$sce#parse `$sce.parseAs($sce.HTML, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ - // normalize IE bug (http://bugs.jquery.com/ticket/1450) - status = status == 1223 ? 204 : status; + /** + * @ngdoc method + * @name ng.$sce#parseAsCss + * @methodOf ng.$sce + * + * @description + * Shorthand method. `$sce.parseAsCss(value)` → {@link ng.$sce#parse `$sce.parseAs($sce.CSS, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ - callback(status, response, headersString); - $browser.$$completeOutstandingRequest(noop); - } - }; + /** + * @ngdoc method + * @name ng.$sce#parseAsUrl + * @methodOf ng.$sce + * + * @description + * Shorthand method. `$sce.parseAsUrl(value)` → {@link ng.$sce#parse `$sce.parseAs($sce.URL, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ - function jsonpReq(url, done) { - // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: - // - fetches local scripts via XHR and evals them - // - adds and immediately removes script elements from the document - var script = rawDocument.createElement('script'), - doneWrapper = function() { - rawDocument.body.removeChild(script); - if (done) done(); - }; + /** + * @ngdoc method + * @name ng.$sce#parseAsResourceUrl + * @methodOf ng.$sce + * + * @description + * Shorthand method. `$sce.parseAsResourceUrl(value)` → {@link ng.$sce#parse `$sce.parseAs($sce.RESOURCE_URL, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ - script.type = 'text/javascript'; - script.src = url; + /** + * @ngdoc method + * @name ng.$sce#parseAsJs + * @methodOf ng.$sce + * + * @description + * Shorthand method. `$sce.parseAsJs(value)` → {@link ng.$sce#parse `$sce.parseAs($sce.JS, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ - if (msie) { - script.onreadystatechange = function() { - if (/loaded|complete/.test(script.readyState)) doneWrapper(); - }; - } else { - script.onload = script.onerror = doneWrapper; - } + // Shorthand delegations. + var parse = sce.parseAs, + getTrusted = sce.getTrusted, + trustAs = sce.trustAs; - rawDocument.body.appendChild(script); - } + angular.forEach(SCE_CONTEXTS, function (enumValue, name) { + var lName = lowercase(name); + sce[camelCase("parse_as_" + lName)] = function (expr) { + return parse(enumValue, expr); + } + sce[camelCase("get_trusted_" + lName)] = function (value) { + return getTrusted(enumValue, value); + } + sce[camelCase("trust_as_" + lName)] = function (value) { + return trustAs(enumValue, value); + } + }); + + return sce; + }]; } /** - * @ngdoc object - * @name ng.$locale + * !!! This is an undocumented "private" service !!! * - * @description - * $locale service provides localization rules for various Angular components. As of right now the - * only public api is: + * @name ng.$sniffer + * @requires $window + * @requires $document * - * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) + * @property {boolean} history Does the browser support html5 history api ? + * @property {boolean} hashchange Does the browser support hashchange event ? + * @property {boolean} transitions Does the browser support CSS transition events ? + * @property {boolean} animations Does the browser support CSS animation events ? + * + * @description + * This is very simple implementation of testing browser's features. */ -function $LocaleProvider(){ - this.$get = function() { - return { - id: 'en-us', +function $SnifferProvider() { + this.$get = ['$window', '$document', function($window, $document) { + var eventSupport = {}, + android = int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), + document = $document[0] || {}, + vendorPrefix, + vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/, + bodyStyle = document.body && document.body.style, + transitions = false, + animations = false, + match; + + if (bodyStyle) { + for(var prop in bodyStyle) { + if(match = vendorRegex.exec(prop)) { + vendorPrefix = match[0]; + vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1); + break; + } + } + transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle)); + animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle)); + + if (android && (!transitions||!animations)) { + transitions = isString(document.body.style.webkitTransition); + animations = isString(document.body.style.webkitAnimation); + } + } - NUMBER_FORMATS: { - DECIMAL_SEP: '.', - GROUP_SEP: ',', - PATTERNS: [ - { // Decimal Pattern - minInt: 1, - minFrac: 0, - maxFrac: 3, - posPre: '', - posSuf: '', - negPre: '-', - negSuf: '', - gSize: 3, - lgSize: 3 - },{ //Currency Pattern - minInt: 1, - minFrac: 2, - maxFrac: 2, - posPre: '\u00A4', - posSuf: '', - negPre: '(\u00A4', - negSuf: ')', - gSize: 3, - lgSize: 3 - } - ], - CURRENCY_SYM: '$' - }, - DATETIME_FORMATS: { - MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' - .split(','), - SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), - DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), - SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), - AMPMS: ['AM','PM'], - medium: 'MMM d, y h:mm:ss a', - short: 'M/d/yy h:mm a', - fullDate: 'EEEE, MMMM d, y', - longDate: 'MMMM d, y', - mediumDate: 'MMM d, y', - shortDate: 'M/d/yy', - mediumTime: 'h:mm:ss a', - shortTime: 'h:mm a' - }, + return { + // Android has history.pushState, but it does not update location correctly + // so let's not use the history API at all. + // http://code.google.com/p/android/issues/detail?id=17471 + // https://github.com/angular/angular.js/issues/904 + history: !!($window.history && $window.history.pushState && !(android < 4)), + hashchange: 'onhashchange' in $window && + // IE8 compatible mode lies + (!document.documentMode || document.documentMode > 7), + hasEvent: function(event) { + // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have + // it. In particular the event is not fired when backspace or delete key are pressed or + // when cut operation is performed. + if (event == 'input' && msie == 9) return false; - pluralCat: function(num) { - if (num === 1) { - return 'one'; + if (isUndefined(eventSupport[event])) { + var divElm = document.createElement('div'); + eventSupport[event] = 'on' + event in divElm; } - return 'other'; - } + + return eventSupport[event]; + }, + csp: document.securityPolicy ? document.securityPolicy.isActive : false, + vendorPrefix: vendorPrefix, + transitions : transitions, + animations : animations }; - }; + }]; } function $TimeoutProvider() { @@ -9490,32 +11333,192 @@ function $TimeoutProvider() { return promise; } - - /** - * @ngdoc function - * @name ng.$timeout#cancel - * @methodOf ng.$timeout - * - * @description - * Cancels a task associated with the `promise`. As a result of this, the promise will be - * resolved with a rejection. - * - * @param {Promise=} promise Promise returned by the `$timeout` function. - * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully - * canceled. - */ - timeout.cancel = function(promise) { - if (promise && promise.$$timeoutId in deferreds) { - deferreds[promise.$$timeoutId].reject('canceled'); - return $browser.defer.cancel(promise.$$timeoutId); + + /** + * @ngdoc function + * @name ng.$timeout#cancel + * @methodOf ng.$timeout + * + * @description + * Cancels a task associated with the `promise`. As a result of this, the promise will be + * resolved with a rejection. + * + * @param {Promise=} promise Promise returned by the `$timeout` function. + * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully + * canceled. + */ + timeout.cancel = function(promise) { + if (promise && promise.$$timeoutId in deferreds) { + deferreds[promise.$$timeoutId].reject('canceled'); + return $browser.defer.cancel(promise.$$timeoutId); + } + return false; + }; + + return timeout; + }]; +} + +function $$UrlUtilsProvider() { + this.$get = [function() { + var urlParsingNode = document.createElement("a"), + // NOTE: The usage of window and document instead of $window and $document here is + // deliberate. This service depends on the specific behavior of anchor nodes created by the + // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and + // cause us to break tests. In addition, when the browser resolves a URL for XHR, it + // doesn't know about mocked locations and resolves URLs to the real document - which is + // exactly the behavior needed here. There is little value is mocking these our for this + // service. + originUrl = resolve(window.location.href, true); + + /** + * @description + * Normalizes and optionally parses a URL. + * + * NOTE: This is a private service. The API is subject to change unpredictably in any commit. + * + * Implementation Notes for non-IE browsers + * ---------------------------------------- + * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, + * results both in the normalizing and parsing of the URL. Normalizing means that a relative + * URL will be resolved into an absolute URL in the context of the application document. + * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related + * properties are all populated to reflect the normalized URL. This approach has wide + * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See + * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html + * + * Implementation Notes for IE + * --------------------------- + * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other + * browsers. However, the parsed components will not be set if the URL assigned did not specify + * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We + * work around that by performing the parsing in a 2nd step by taking a previously normalized + * URL (e.g. by assining to a.href) and assigning it a.href again. This correctly populates the + * properties such as protocol, hostname, port, etc. + * + * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one + * uses the inner HTML approach to assign the URL as part of an HTML snippet - + * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL. + * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception. + * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that + * method and IE < 8 is unsupported. + * + * References: + * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement + * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html + * http://url.spec.whatwg.org/#urlutils + * https://github.com/angular/angular.js/pull/2902 + * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ + * + * @param {string} url The URL to be parsed. + * @param {boolean=} parse When true, returns an object for the parsed URL. Otherwise, returns + * a single string that is the normalized URL. + * @returns {object|string} When parse is true, returns the normalized URL as a string. + * Otherwise, returns an object with the following members. + * + * | member name | Description | + * |===============|================| + * | href | A normalized version of the provided URL if it was not an absolute URL | + * | protocol | The protocol including the trailing colon | + * | host | The host and port (if the port is non-default) of the normalizedUrl | + * + * These fields from the UrlUtils interface are currently not needed and hence not returned. + * + * | member name | Description | + * |===============|================| + * | hostname | The host without the port of the normalizedUrl | + * | pathname | The path following the host in the normalizedUrl | + * | hash | The URL hash if present | + * | search | The query string | + * + */ + function resolve(url, parse) { + var href = url; + if (msie) { + // Normalize before parse. Refer Implementation Notes on why this is + // done in two steps on IE. + urlParsingNode.setAttribute("href", href); + href = urlParsingNode.href; + } + urlParsingNode.setAttribute('href', href); + + if (!parse) { + return urlParsingNode.href; + } + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol, + host: urlParsingNode.host + // Currently unused and hence commented out. + // hostname: urlParsingNode.hostname, + // port: urlParsingNode.port, + // pathname: urlParsingNode.pathname, + // hash: urlParsingNode.hash, + // search: urlParsingNode.search + }; + } + + return { + resolve: resolve, + /** + * Parse a request URL and determine whether this is a same-origin request as the application document. + * + * @param {string|object} requestUrl The url of the request as a string that will be resolved + * or a parsed URL object. + * @returns {boolean} Whether the request is for the same origin as the application document. + */ + isSameOrigin: function isSameOrigin(requestUrl) { + var parsed = (typeof requestUrl === 'string') ? resolve(requestUrl, true) : requestUrl; + return (parsed.protocol === originUrl.protocol && + parsed.host === originUrl.host); } - return false; }; - - return timeout; }]; } +/** + * @ngdoc object + * @name ng.$window + * + * @description + * A reference to the browser's `window` object. While `window` + * is globally available in JavaScript, it causes testability problems, because + * it is a global variable. In angular we always refer to it through the + * `$window` service, so it may be overridden, removed or mocked for testing. + * + * Expressions, like the one defined for the `ngClick` directive in the example + * below, are evaluated with respect to the current scope. Therefore, there is + * no risk of inadvertently coding in a dependency on a global value in such an + * expression. + * + * @example + + + +
+ + +
+
+ + it('should display the greeting in the input box', function() { + input('greeting').enter('Hello, E2E Tests'); + // If we click the button it will block the test runner + // element(':button').click(); + }); + +
+ */ +function $WindowProvider(){ + this.$get = valueFn(window); +} + /** * @ngdoc object * @name ng.$filterProvider @@ -9546,7 +11549,7 @@ function $TimeoutProvider() { * } * * - * The filter function is registered with the `$injector` under the filter name suffixe with `Filter`. + * The filter function is registered with the `$injector` under the filter name suffix with `Filter`. *
  *   it('should be the same instance', inject(
  *     function($filterProvider) {
@@ -9650,6 +11653,22 @@ function $FilterProvider($provide) {
  *     called for each element of `array`. The final result is an array of those elements that
  *     the predicate returned true for.
  *
+ * @param {function(expected, actual)|true|undefined} comparator Comparator which is used in
+ *     determining if the expected value (from the filter expression) and actual value (from
+ *     the object in the array) should be considered a match.
+ *
+ *   Can be one of:
+ *
+ *     - `function(expected, actual)`:
+ *       The function will be given the object value and the predicate value to compare and
+ *       should return true if the item should be included in filtered result.
+ *
+ *     - `true`: A shorthand for `function(expected, actual) { return angular.equals(expected, actual)}`.
+ *       this is essentially strict comparison of expected and actual.
+ *
+ *     - `false|undefined`: A short hand for a function which will look for a substring match in case
+ *       insensitive way.
+ *
  * @example
    
      
@@ -9657,7 +11676,8 @@ function $FilterProvider($provide) {
                                 {name:'Mary', phone:'800-BIG-MARY'},
                                 {name:'Mike', phone:'555-4321'},
                                 {name:'Adam', phone:'555-5678'},
-                                {name:'Julie', phone:'555-8765'}]">
+                                {name:'Julie', phone:'555-8765'},
+                                {name:'Juliette', phone:'555-5678'}]">
 
        Search: 
        
@@ -9671,9 +11691,10 @@ function $FilterProvider($provide) {
        Any: 
Name only
Phone only
+ Equality
- + @@ -9693,13 +11714,19 @@ function $FilterProvider($provide) { it('should search in specific fields when filtering with a predicate object', function() { input('search.$').enter('i'); expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). - toEqual(['Mary', 'Mike', 'Julie']); + toEqual(['Mary', 'Mike', 'Julie', 'Juliette']); + }); + it('should use a equal comparison when comparator is true', function() { + input('search.name').enter('Julie'); + input('strict').check(); + expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). + toEqual(['Julie']); }); */ function filterFilter() { - return function(array, expression) { + return function(array, expression, comperator) { if (!isArray(array)) return array; var predicates = []; predicates.check = function(value) { @@ -9710,20 +11737,43 @@ function filterFilter() { } return true; }; + switch(typeof comperator) { + case "function": + break; + case "boolean": + if(comperator == true) { + comperator = function(obj, text) { + return angular.equals(obj, text); + } + break; + } + default: + comperator = function(obj, text) { + text = (''+text).toLowerCase(); + return (''+obj).toLowerCase().indexOf(text) > -1 + }; + } var search = function(obj, text){ - if (text.charAt(0) === '!') { + if (typeof text == 'string' && text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": - return ('' + obj).toLowerCase().indexOf(text) > -1; + return comperator(obj, text); case "object": - for ( var objKey in obj) { - if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { - return true; - } + switch (typeof text) { + case "object": + return comperator(obj, text); + break; + default: + for ( var objKey in obj) { + if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { + return true; + } + } + break; } return false; case "array": @@ -9746,19 +11796,18 @@ function filterFilter() { for (var key in expression) { if (key == '$') { (function() { - var text = (''+expression[key]).toLowerCase(); - if (!text) return; + if (!expression[key]) return; + var path = key predicates.push(function(value) { - return search(value, text); + return search(value, expression[path]); }); })(); } else { (function() { + if (!expression[key]) return; var path = key; - var text = (''+expression[key]).toLowerCase(); - if (!text) return; predicates.push(function(value) { - return search(getter(value, path), text); + return search(getter(value,path), expression[path]); }); })(); } @@ -9843,7 +11892,9 @@ function currencyFilter($locale) { * If the input is not a number an empty string is returned. * * @param {number|string} number Number to format. - * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to. + * @param {(number|string)=} fractionSize Number of decimal places to round the number to. + * If this is not provided then the fraction size is computed from the current locale's number + * formatting pattern. In the case of the default locale, it will be 3. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example @@ -9950,6 +12001,11 @@ function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { } if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); + } else { + + if (fractionSize > 0 && number > -1 && number < 1) { + formatedText = number.toFixed(fractionSize); + } } parts.push(isNegative ? pattern.negPre : pattern.posPre); @@ -10024,6 +12080,9 @@ var DATE_FORMATS = { m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), + // while ISO 8601 requires fractions to be prefixed with `.` or `,` + // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions + sss: dateGetter('Milliseconds', 3), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: ampmGetter, @@ -10062,6 +12121,7 @@ var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+ * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) + * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) * @@ -10073,7 +12133,7 @@ var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+ * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale * (e.g. Friday, September 3, 2010) - * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010 + * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010) * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) @@ -10081,7 +12141,7 @@ var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+ * * `format` string can contain literal values. These need to be quoted with single quotes (e.g. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence - * (e.g. `"h o''clock"`). + * (e.g. `"h 'o''clock'"`). * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its @@ -10118,18 +12178,26 @@ function dateFilter($locale) { var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; - function jsonStringToDate(string){ + // 1 2 3 4 5 6 7 8 9 10 11 + function jsonStringToDate(string) { var match; if (match = string.match(R_ISO8601_STR)) { var date = new Date(0), tzHour = 0, - tzMin = 0; + tzMin = 0, + dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, + timeSetter = match[8] ? date.setUTCHours : date.setHours; + if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } - date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3])); - date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0)); + dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3])); + var h = int(match[4]||0) - tzHour; + var m = int(match[5]||0) - tzMin + var s = int(match[6]||0); + var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000); + timeSetter.call(date, h, m, s, ms); return date; } return string; @@ -10243,20 +12311,20 @@ var uppercaseFilter = valueFn(uppercase); * @function * * @description - * Creates a new array containing only a specified number of elements in an array. The elements - * are taken from either the beginning or the end of the source array, as specified by the - * value and sign (positive or negative) of `limit`. + * Creates a new array or string containing only a specified number of elements. The elements + * are taken from either the beginning or the end of the source array or string, as specified by + * the value and sign (positive or negative) of `limit`. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * - * @param {Array} array Source array to be limited. - * @param {string|Number} limit The length of the returned array. If the `limit` number is - * positive, `limit` number of items from the beginning of the source array are copied. - * If the number is negative, `limit` number of items from the end of the source array are - * copied. The `limit` will be trimmed if it exceeds `array.length` - * @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit` - * elements. + * @param {Array|string} input Source array or string to be limited. + * @param {string|number} limit The length of the returned array or string. If the `limit` number + * is positive, `limit` number of items from the beginning of the source array/string are copied. + * If the number is negative, `limit` number of items from the end of the source array/string + * are copied. The `limit` will be trimmed if it exceeds `array.length` + * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array + * had less than `limit` elements. * * @example @@ -10264,59 +12332,76 @@ var uppercaseFilter = valueFn(uppercase);
- Limit {{numbers}} to: -

Output: {{ numbers | limitTo:limit }}

+ Limit {{numbers}} to: +

Output numbers: {{ numbers | limitTo:numLimit }}

+ Limit {{letters}} to: +

Output letters: {{ letters | limitTo:letterLimit }}

- it('should limit the numer array to first three items', function() { - expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3'); - expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]'); + it('should limit the number array to first three items', function() { + expect(element('.doc-example-live input[ng-model=numLimit]').val()).toBe('3'); + expect(element('.doc-example-live input[ng-model=letterLimit]').val()).toBe('3'); + expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3]'); + expect(binding('letters | limitTo:letterLimit')).toEqual('abc'); }); it('should update the output when -3 is entered', function() { - input('limit').enter(-3); - expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]'); + input('numLimit').enter(-3); + input('letterLimit').enter(-3); + expect(binding('numbers | limitTo:numLimit')).toEqual('[7,8,9]'); + expect(binding('letters | limitTo:letterLimit')).toEqual('ghi'); }); it('should not exceed the maximum size of input array', function() { - input('limit').enter(100); - expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]'); + input('numLimit').enter(100); + input('letterLimit').enter(100); + expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3,4,5,6,7,8,9]'); + expect(binding('letters | limitTo:letterLimit')).toEqual('abcdefghi'); });
*/ function limitToFilter(){ - return function(array, limit) { - if (!(array instanceof Array)) return array; + return function(input, limit) { + if (!isArray(input) && !isString(input)) return input; + limit = int(limit); + + if (isString(input)) { + //NaN check on limit + if (limit) { + return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); + } else { + return ""; + } + } + var out = [], i, n; - // check that array is iterable - if (!array || !(array instanceof Array)) - return out; - // if abs(limit) exceeds maximum length, trim it - if (limit > array.length) - limit = array.length; - else if (limit < -array.length) - limit = -array.length; + if (limit > input.length) + limit = input.length; + else if (limit < -input.length) + limit = -input.length; if (limit > 0) { i = 0; n = limit; } else { - i = array.length + limit; - n = array.length; + i = input.length + limit; + n = input.length; } for (; i} expression A predicate to be @@ -10502,7 +12587,7 @@ var htmlAnchorDirective = valueFn({ } return function(scope, element) { - element.bind('click', function(event){ + element.on('click', function(event){ // if we have no href url, then don't navigate anywhere. if (!element.attr('href')) { event.preventDefault(); @@ -10617,6 +12702,31 @@ var htmlAnchorDirective = valueFn({ * @param {template} ngSrc any string which can contain `{{}}` markup. */ +/** + * @ngdoc directive + * @name ng.directive:ngSrcset + * @restrict A + * + * @description + * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't + * work right: The browser will fetch from the URL with the literal + * text `{{hash}}` until Angular replaces the expression inside + * `{{hash}}`. The `ngSrcset` directive solves this problem. + * + * The buggy way to write it: + *
+ * 
+ * 
+ * + * The correct way to write it: + *
+ * 
+ * 
+ * + * @element IMG + * @param {template} ngSrcset any string which can contain `{{}}` markup. + */ + /** * @ngdoc directive * @name ng.directive:ngDisabled @@ -10686,42 +12796,6 @@ var htmlAnchorDirective = valueFn({ */ -/** - * @ngdoc directive - * @name ng.directive:ngMultiple - * @restrict A - * - * @description - * The HTML specs do not require browsers to preserve the special attributes such as multiple. - * (The presence of them means true and absence means false) - * This prevents the angular compiler from correctly retrieving the binding expression. - * To solve this problem, we introduce the `ngMultiple` directive. - * - * @example - - - Check me check multiple:
- -
- - it('should toggle multiple', function() { - expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy(); - input('checked').check(); - expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy(); - }); - -
- * - * @element SELECT - * @param {expression} ngMultiple Angular expression that will be evaluated. - */ - - /** * @ngdoc directive * @name ng.directive:ngReadonly @@ -10784,12 +12858,46 @@ var htmlAnchorDirective = valueFn({ * @param {string} expression Angular expression that will be evaluated. */ +/** + * @ngdoc directive + * @name ng.directive:ngOpen + * @restrict A + * + * @description + * The HTML specs do not require browsers to preserve the special attributes such as open. + * (The presence of them means true and absence means false) + * This prevents the angular compiler from correctly retrieving the binding expression. + * To solve this problem, we introduce the `ngOpen` directive. + * + * @example + + + Check me check multiple:
+
+ Show/Hide me +
+
+ + it('should toggle open', function() { + expect(element('#details').prop('open')).toBeFalsy(); + input('open').check(); + expect(element('#details').prop('open')).toBeTruthy(); + }); + +
+ * + * @element DETAILS + * @param {string} expression Angular expression that will be evaluated. + */ var ngAttributeAliasDirectives = {}; // boolean attrs are evaluated forEach(BOOLEAN_ATTR, function(propName, attrName) { + // binding to multiple is not supported + if (propName == "multiple") return; + var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { @@ -10806,8 +12914,8 @@ forEach(BOOLEAN_ATTR, function(propName, attrName) { }); -// ng-src, ng-href are interpolated -forEach(['src', 'href'], function(attrName) { +// ng-src, ng-srcset, ng-href are interpolated +forEach(['src', 'srcset', 'href'], function(attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { @@ -10834,7 +12942,8 @@ var nullFormCtrl = { $addControl: noop, $removeControl: noop, $setValidity: noop, - $setDirty: noop + $setDirty: noop, + $setPristine: noop }; /** @@ -10866,10 +12975,11 @@ function FormController(element, attrs) { var form = this, parentForm = element.parent().controller('form') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid - errors = form.$error = {}; + errors = form.$error = {}, + controls = []; // init state - form.$name = attrs.name; + form.$name = attrs.name || attrs.ngForm; form.$dirty = false; form.$pristine = true; form.$valid = true; @@ -10889,12 +12999,34 @@ function FormController(element, attrs) { addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } + /** + * @ngdoc function + * @name ng.directive:form.FormController#$addControl + * @methodOf ng.directive:form.FormController + * + * @description + * Register a control with the form. + * + * Input elements using ngModelController do this automatically when they are linked. + */ form.$addControl = function(control) { + controls.push(control); + if (control.$name && !form.hasOwnProperty(control.$name)) { form[control.$name] = control; } }; + /** + * @ngdoc function + * @name ng.directive:form.FormController#$removeControl + * @methodOf ng.directive:form.FormController + * + * @description + * Deregister a control from the form. + * + * Input elements using ngModelController do this automatically when they are destroyed. + */ form.$removeControl = function(control) { if (control.$name && form[control.$name] === control) { delete form[control.$name]; @@ -10902,8 +13034,20 @@ function FormController(element, attrs) { forEach(errors, function(queue, validationToken) { form.$setValidity(validationToken, true, control); }); + + arrayRemove(controls, control); }; + /** + * @ngdoc function + * @name ng.directive:form.FormController#$setValidity + * @methodOf ng.directive:form.FormController + * + * @description + * Sets the validity of a form control. + * + * This method will also propagate to parent forms. + */ form.$setValidity = function(validationToken, isValid, control) { var queue = errors[validationToken]; @@ -10942,6 +13086,17 @@ function FormController(element, attrs) { } }; + /** + * @ngdoc function + * @name ng.directive:form.FormController#$setDirty + * @methodOf ng.directive:form.FormController + * + * @description + * Sets the form to a dirty state. + * + * This method can be called to add the 'ng-dirty' class and set the form to a dirty + * state (ng-dirty class). This method will also propagate to parent forms. + */ form.$setDirty = function() { element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); form.$dirty = true; @@ -10949,6 +13104,29 @@ function FormController(element, attrs) { parentForm.$setDirty(); }; + /** + * @ngdoc function + * @name ng.directive:form.FormController#$setPristine + * @methodOf ng.directive:form.FormController + * + * @description + * Sets the form to its pristine state. + * + * This method can be called to remove the 'ng-dirty' class and set the form to its pristine + * state (ng-pristine class). This method will also propagate to all the controls contained + * in this form. + * + * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after + * saving or resetting it. + */ + form.$setPristine = function () { + element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS); + form.$dirty = false; + form.$pristine = true; + forEach(controls, function(control) { + control.$setPristine(); + }); + }; } @@ -11083,7 +13261,7 @@ var formDirectiveFactory = function(isNgForm) { // unregister the preventDefault listener so that we don't not leak memory but in a // way that will achieve the prevention of the default action. - formElement.bind('$destroy', function() { + formElement.on('$destroy', function() { $timeout(function() { removeEventListenerFn(formElement[0], 'submit', preventDefaultListener); }, 0, false); @@ -11094,13 +13272,13 @@ var formDirectiveFactory = function(isNgForm) { alias = attr.name || attr.ngForm; if (alias) { - scope[alias] = controller; + setter(scope, alias, controller, alias); } if (parentFormCtrl) { - formElement.bind('$destroy', function() { + formElement.on('$destroy', function() { parentFormCtrl.$removeControl(controller); if (alias) { - scope[alias] = undefined; + setter(scope, alias, undefined, alias); } extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards }); @@ -11118,7 +13296,7 @@ var formDirective = formDirectiveFactory(); var ngFormDirective = formDirectiveFactory(true); var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; -var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/; +var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/; var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; var inputType = { @@ -11145,6 +13323,8 @@ var inputType = { * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. + * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trimming the + * input. * * @example @@ -11152,12 +13332,12 @@ var inputType = {
Single word: + ng-pattern="word" required ng-trim="false"> Required! @@ -11186,6 +13366,12 @@ var inputType = { input('text').enter('hello world'); expect(binding('myForm.input.$valid')).toEqual('false'); }); + + it('should not be trimmed', function() { + input('text').enter('untrimmed '); + expect(binding('text')).toEqual('untrimmed '); + expect(binding('myForm.input.$valid')).toEqual('true'); + });
*/ @@ -11229,9 +13415,9 @@ var inputType = { Number: - + Required! - + Not valid number! value = {{value}}
myForm.input.$valid = {{myForm.input.$valid}}
@@ -11352,6 +13538,8 @@ var inputType = { * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. * * @example @@ -11499,7 +13687,14 @@ function isEmpty(value) { function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { var listener = function() { - var value = trim(element.val()); + var value = element.val(); + + // By default we will trim the value + // If the attribute ng-trim exists we will avoid trimming + // e.g. + if (toBoolean(attr.ngTrim || 'T')) { + value = trim(value); + } if (ctrl.$viewValue !== value) { scope.$apply(function() { @@ -11511,7 +13706,7 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the // input event on backspace, delete or cut if ($sniffer.hasEvent('input')) { - element.bind('input', listener); + element.on('input', listener); } else { var timeout; @@ -11524,7 +13719,7 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { } }; - element.bind('keydown', function(event) { + element.on('keydown', function(event) { var key = event.keyCode; // ignore @@ -11535,11 +13730,11 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { }); // if user paste into input using mouse, we need "change" event to catch it - element.bind('change', listener); + element.on('change', listener); // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it if ($sniffer.hasEvent('paste')) { - element.bind('paste cut', deferListener); + element.on('paste cut', deferListener); } } @@ -11550,7 +13745,8 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { // pattern validator var pattern = attr.ngPattern, - patternValidator; + patternValidator, + match; var validate = function(regexp, value) { if (isEmpty(value) || regexp.test(value)) { @@ -11563,8 +13759,9 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { }; if (pattern) { - if (pattern.match(/^\/(.*)\/$/)) { - pattern = new RegExp(pattern.substr(1, pattern.length - 2)); + match = pattern.match(/^\/(.*)\/([gim]*)$/); + if (match) { + pattern = new RegExp(match[1], match[2]); patternValidator = function(value) { return validate(pattern, value) }; @@ -11573,7 +13770,9 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { var patternObj = scope.$eval(pattern); if (!patternObj || !patternObj.test) { - throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj); + throw minErr('ngPattern')('noregexp', + 'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern, + patternObj, startingTag(element)); } return validate(patternObj, value); }; @@ -11720,7 +13919,7 @@ function radioInputType(scope, element, attr, ctrl) { element.attr('name', nextUid()); } - element.bind('click', function() { + element.on('click', function() { if (element[0].checked) { scope.$apply(function() { ctrl.$setViewValue(attr.value); @@ -11743,7 +13942,7 @@ function checkboxInputType(scope, element, attr, ctrl) { if (!isString(trueValue)) trueValue = true; if (!isString(falseValue)) falseValue = false; - element.bind('click', function() { + element.on('click', function() { scope.$apply(function() { ctrl.$setViewValue(element[0].checked); }); @@ -11910,13 +14109,26 @@ var VALID_CLASS = 'ng-valid', * * @property {string} $viewValue Actual string value in the view. * @property {*} $modelValue The value in the model, that the control is bound to. - * @property {Array.} $parsers Whenever the control reads value from the DOM, it executes - * all of these functions to sanitize / convert the value as well as validate. - * - * @property {Array.} $formatters Whenever the model value changes, it executes all of - * these functions to convert the value as well as validate. - * - * @property {Object} $error An bject hash with all errors as keys. + * @property {Array.} $parsers Array of functions to execute, as a pipeline, whenever + the control reads value from the DOM. Each function is called, in turn, passing the value + through to the next. Used to sanitize / convert the value as well as validation. + For validation, the parsers should update the validity state using + {@link ng.directive:ngModel.NgModelController#$setValidity $setValidity()}, + and return `undefined` for invalid values. + + * + * @property {Array.} $formatters Array of functions to execute, as a pipeline, whenever + the model value changes. Each function is called, in turn, passing the value through to the + next. Used to format / convert values for display in the control and validation. + *
+ *      function formatter(value) {
+ *        if (value) {
+ *          return value.toUpperCase();
+ *        }
+ *      }
+ *      ngModel.$formatters.push(formatter);
+ *      
+ * @property {Object} $error An object hash with all errors as keys. * * @property {boolean} $pristine True if user has not interacted with the control yet. * @property {boolean} $dirty True if user has already interacted with the control. @@ -11930,6 +14142,10 @@ var VALID_CLASS = 'ng-valid', * specifically does not contain any logic which deals with DOM rendering or listening to * DOM events. The `NgModelController` is meant to be extended by other directives where, the * directive provides DOM manipulation and the `NgModelController` provides the data-binding. + * Note that you cannot use `NgModelController` in a directive with an isolated scope, + * as, in that case, the `ng-model` value gets put into the isolated scope and does not get + * propogated to the parent scope. + * * * This example shows how to use `NgModelController` with a custom control to achieve * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) @@ -11963,14 +14179,20 @@ var VALID_CLASS = 'ng-valid', }; // Listen for change events to enable binding - element.bind('blur keyup change', function() { + element.on('blur keyup change', function() { scope.$apply(read); }); read(); // initialize // Write data to the model function read() { - ngModel.$setViewValue(element.html()); + var html = element.html(); + // When we clear the content editable the browser leaves a
behind + // If strip-br attribute is provided then we strip this out + if( attrs.stripBr && html == '
' ) { + html = ''; + } + ngModel.$setViewValue(html); } } }; @@ -11980,6 +14202,7 @@ var VALID_CLASS = 'ng-valid',
Change me!
Required!
@@ -12016,8 +14239,8 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ ngModelSet = ngModelGet.assign; if (!ngModelSet) { - throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel + - ' (' + startingTag($element) + ')'); + throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}", + $attr.ngModel, startingTag($element)); } /** @@ -12089,6 +14312,22 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ parentForm.$setValidity(validationErrorKey, isValid, this); }; + /** + * @ngdoc function + * @name ng.directive:ngModel.NgModelController#$setPristine + * @methodOf ng.directive:ngModel.NgModelController + * + * @description + * Sets the control to its pristine state. + * + * This method can be called to remove the 'ng-dirty' class and set the control to its pristine + * state (ng-pristine class). + */ + this.$setPristine = function () { + this.$dirty = false; + this.$pristine = true; + $element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS); + }; /** * @ngdoc function @@ -12102,8 +14341,8 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ * For example {@link ng.directive:input input} or * {@link ng.directive:select select} directives call it. * - * It internally calls all `parsers` and if resulted value is valid, updates the model and - * calls all registered change listeners. + * It internally calls all `$parsers` (including validators) and updates the `$modelValue` and the actual model path. + * Lastly it calls all registered change listeners. * * @param {string} value Value from the view. */ @@ -12168,8 +14407,9 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ * @element input * * @description - * Is directive that tells Angular to do two-way data binding. It works together with `input`, - * `select`, `textarea`. You can easily write your own directives to use `ngModel` as well. + * Is a directive that tells Angular to do two-way data binding. It works together with `input`, + * `select`, `textarea` and even custom form controls that use {@link ng.directive:ngModel.NgModelController + * NgModelController} exposed by this directive. * * `ngModel` is responsible for: * @@ -12180,6 +14420,10 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ * - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`), * - register the control with parent {@link ng.directive:form form}. * + * Note: `ngModel` will try to bind to the property given by evaluating the expression on the + * current scope. If the property doesn't already exist on this scope, it will be created + * implicitly and added to the scope. + * * For basic examples, how to use `ngModel`, see: * * - {@link ng.directive:input input} @@ -12205,7 +14449,7 @@ var ngModelDirective = function() { formCtrl.$addControl(modelCtrl); - element.bind('$destroy', function() { + element.on('$destroy', function() { formCtrl.$removeControl(modelCtrl); }); } @@ -12320,8 +14564,9 @@ var requiredDirective = function() { List: - + Required! +
names = {{names}}
myForm.namesInput.$valid = {{myForm.namesInput.$valid}}
myForm.namesInput.$error = {{myForm.namesInput.$error}}
@@ -12333,12 +14578,14 @@ var requiredDirective = function() { it('should initialize to model', function() { expect(binding('names')).toEqual('["igor","misko","vojta"]'); expect(binding('myForm.namesInput.$valid')).toEqual('true'); + expect(element('span.error').css('display')).toBe('none'); }); it('should be invalid if empty', function() { input('names').enter(''); expect(binding('names')).toEqual('[]'); expect(binding('myForm.namesInput.$valid')).toEqual('false'); + expect(element('span.error').css('display')).not().toBe('none'); });
@@ -12388,7 +14635,7 @@ var ngValueDirective = function() { } else { return function(scope, elm, attr) { scope.$watch(attr.ngValue, function valueWatchAction(value) { - attr.$set('value', value, false); + attr.$set('value', value); }); }; } @@ -12408,10 +14655,9 @@ var ngValueDirective = function() { * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like * `{{ expression }}` which is similar but less verbose. * - * One scenario in which the use of `ngBind` is preferred over `{{ expression }}` binding is when - * it's desirable to put bindings into template that is momentarily displayed by the browser in its - * raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the - * bindings invisible to the user while the page is loading. + * It is preferrable to use `ngBind` instead of `{{ expression }}` when a template is momentarily + * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an + * element attribute, it makes the bindings invisible to the user while the page is loading. * * An alternative solution to this problem would be using the * {@link ng.directive:ngCloak ngCloak} directive. @@ -12457,10 +14703,11 @@ var ngBindDirective = ngDirective(function(scope, element, attr) { * * @description * The `ngBindTemplate` directive specifies that the element - * text should be replaced with the template in ngBindTemplate. - * Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}` - * expressions. (This is required since some HTML elements - * can not have SPAN elements such as TITLE, or OPTION to name a few.) + * text content should be replaced with the interpolation of the template + * in the `ngBindTemplate` attribute. + * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` + * expressions. This directive is needed since some HTML elements + * (such as TITLE and OPTION) cannot contain SPAN elements. * * @element ANY * @param {string} ngBindTemplate template of form @@ -12512,23 +14759,27 @@ var ngBindTemplateDirective = ['$interpolate', function($interpolate) { /** * @ngdoc directive - * @name ng.directive:ngBindHtmlUnsafe + * @name ng.directive:ngBindHtml * * @description * Creates a binding that will innerHTML the result of evaluating the `expression` into the current - * element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if - * {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too - * restrictive and when you absolutely trust the source of the content you are binding to. + * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link + * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize` + * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in + * core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to + * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example + * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}. * - * See {@link ngSanitize.$sanitize $sanitize} docs for examples. + * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you + * will have an exception (instead of an exploit.) * * @element ANY - * @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate. + * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. */ -var ngBindHtmlUnsafeDirective = [function() { +var ngBindHtmlDirective = ['$sce', function($sce) { return function(scope, element, attr) { - element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe); - scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) { + element.addClass('ng-binding').data('$binding', attr.ngBindHtml); + scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function ngBindHtmlWatchAction(value) { element.html(value || ''); }); }; @@ -12536,59 +14787,71 @@ var ngBindHtmlUnsafeDirective = [function() { function classDirective(name, selector) { name = 'ngClass' + name; - return ngDirective(function(scope, element, attr) { - var oldVal = undefined; + return function() { + return { + restrict: 'AC', + link: function(scope, element, attr) { + var oldVal = undefined; - scope.$watch(attr[name], ngClassWatchAction, true); + scope.$watch(attr[name], ngClassWatchAction, true); - attr.$observe('class', function(value) { - var ngClass = scope.$eval(attr[name]); - ngClassWatchAction(ngClass, ngClass); - }); + attr.$observe('class', function(value) { + ngClassWatchAction(scope.$eval(attr[name])); + }); - if (name !== 'ngClass') { - scope.$watch('$index', function($index, old$index) { - var mod = $index & 1; - if (mod !== old$index & 1) { - if (mod === selector) { - addClass(scope.$eval(attr[name])); - } else { - removeClass(scope.$eval(attr[name])); + if (name !== 'ngClass') { + scope.$watch('$index', function($index, old$index) { + var mod = $index & 1; + if (mod !== old$index & 1) { + if (mod === selector) { + addClass(scope.$eval(attr[name])); + } else { + removeClass(scope.$eval(attr[name])); + } + } + }); + } + + + function ngClassWatchAction(newVal) { + if (selector === true || scope.$index % 2 === selector) { + if (oldVal && !equals(newVal,oldVal)) { + removeClass(oldVal); + } + addClass(newVal); } + oldVal = copy(newVal); } - }); - } - function ngClassWatchAction(newVal) { - if (selector === true || scope.$index % 2 === selector) { - if (oldVal && !equals(newVal,oldVal)) { - removeClass(oldVal); + function removeClass(classVal) { + attr.$removeClass(flattenClasses(classVal)); } - addClass(newVal); - } - oldVal = copy(newVal); - } - function removeClass(classVal) { - if (isObject(classVal) && !isArray(classVal)) { - classVal = map(classVal, function(v, k) { if (v) return k }); - } - element.removeClass(isArray(classVal) ? classVal.join(' ') : classVal); - } + function addClass(classVal) { + attr.$addClass(flattenClasses(classVal)); + } + function flattenClasses(classVal) { + if(isArray(classVal)) { + return classVal.join(' '); + } else if (isObject(classVal)) { + var classes = [], i = 0; + forEach(classVal, function(v, k) { + if (v) { + classes.push(k); + } + }); + return classes.join(' '); + } - function addClass(classVal) { - if (isObject(classVal) && !isArray(classVal)) { - classVal = map(classVal, function(v, k) { if (v) return k }); - } - if (classVal) { - element.addClass(isArray(classVal) ? classVal.join(' ') : classVal); + return classVal; + }; } - } - }); + }; + }; } /** @@ -12596,21 +14859,86 @@ function classDirective(name, selector) { * @name ng.directive:ngClass * * @description - * The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an - * expression that represents all classes to be added. + * The `ngClass` allows you to set CSS classes on HTML an element, dynamically, by databinding + * an expression that represents all classes to be added. * * The directive won't add duplicate classes if a particular class was already set. * * When the expression changes, the previously added classes are removed and only then the * new classes are added. * + * @animations + * add - happens just before the class is applied to the element + * remove - happens just before the class is removed from the element + * * @element ANY * @param {expression} ngClass {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class - * names, an array, or a map of class names to boolean values. + * names, an array, or a map of class names to boolean values. In the case of a map, the + * names of the properties whose values are truthy will be added as css classes to the + * element. * - * @example + * @example Example that demostrates basic bindings via ngClass directive. + +

Map Syntax Example

+ bold + strike + red +
+

Using String Syntax

+ +
+

Using Array Syntax

+
+
+
+
+ + .strike { + text-decoration: line-through; + } + .bold { + font-weight: bold; + } + .red { + color: red; + } + + + it('should let you toggle the class', function() { + + expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/bold/); + expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/red/); + + input('bold').check(); + expect(element('.doc-example-live p:first').prop('className')).toMatch(/bold/); + + input('red').check(); + expect(element('.doc-example-live p:first').prop('className')).toMatch(/red/); + }); + + it('should let you toggle string example', function() { + expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe(''); + input('style').enter('red'); + expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe('red'); + }); + + it('array example should have 3 classes', function() { + expect(element('.doc-example-live p:last').prop('className')).toBe(''); + input('style1').enter('bold'); + input('style2').enter('strike'); + input('style3').enter('red'); + expect(element('.doc-example-live p:last').prop('className')).toBe('bold strike red'); + }); + +
+ + ## Animations + + Example that demostrates how addition and removal of classes can be animated. + + @@ -12618,8 +14946,22 @@ function classDirective(name, selector) { Sample Text - .my-class { + .my-class-add, .my-class-remove { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + } + + .my-class, + .my-class-add.my-class-add-active { color: red; + font-size:3em; + } + + .my-class-remove.my-class-remove-active { + font-size:1.0em; + color:black; } @@ -12746,14 +15088,14 @@ var ngClassEvenDirective = classDirective('Even', 1); * directive to avoid the undesirable flicker effect caused by the html template display. * * The directive can be applied to the `` element, but typically a fine-grained application is - * prefered in order to benefit from progressive rendering of the browser view. + * preferred in order to benefit from progressive rendering of the browser view. * * `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and * `angular.min.js` files. Following is the css rule: * *
  * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
- *   display: none;
+ *   display: none !important;
  * }
  * 
* @@ -12811,13 +15153,14 @@ var ngCloakDirective = ngDirective({ * * Controller — The `ngController` directive specifies a Controller class; the class has * methods that typically express the business logic behind the application. * - * Note that an alternative way to define controllers is via the {@link ng.$route $route} service. + * Note that an alternative way to define controllers is via the {@link ngRoute.$route $route} service. * * @element ANY * @scope * @param {expression} ngController Name of a globally accessible constructor function or an * {@link guide/expression expression} that on the current scope evaluates to a - * constructor function. + * constructor function. The controller instance can further be published into the scope + * by adding `as localName` the controller name attribute. * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and @@ -12825,11 +15168,75 @@ var ngCloakDirective = ngDirective({ * easily be called from the angular markup. Notice that the scope becomes the `this` for the * controller's instance. This allows for easy access to the view data from the controller. Also * notice that any changes to the data are automatically reflected in the View without the need - * for a manual update. + * for a manual update. The example is included in two different declaration styles based on + * your style preferences. +
+ Name: + [ greet ]
+ Contact: +
    +
  • + + + [ clear + | X ] +
  • +
  • [ add ]
  • +
+
+
+ + it('should check controller as', function() { + expect(element('#ctrl-as-exmpl>:input').val()).toBe('John Smith'); + expect(element('#ctrl-as-exmpl li:nth-child(1) input').val()) + .toBe('408 555 1212'); + expect(element('#ctrl-as-exmpl li:nth-child(2) input').val()) + .toBe('john.smith@example.org'); + + element('#ctrl-as-exmpl li:first a:contains("clear")').click(); + expect(element('#ctrl-as-exmpl li:first input').val()).toBe(''); + + element('#ctrl-as-exmpl li:last a:contains("add")').click(); + expect(element('#ctrl-as-exmpl li:nth-child(3) input').val()) + .toBe('yourname@example.org'); + }); + +
+ + + -
+
Name: [ greet ]
Contact: @@ -12874,21 +15281,22 @@ var ngCloakDirective = ngDirective({ it('should check controller', function() { - expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); - expect(element('.doc-example-live li:nth-child(1) input').val()) + expect(element('#ctrl-exmpl>:input').val()).toBe('John Smith'); + expect(element('#ctrl-exmpl li:nth-child(1) input').val()) .toBe('408 555 1212'); - expect(element('.doc-example-live li:nth-child(2) input').val()) + expect(element('#ctrl-exmpl li:nth-child(2) input').val()) .toBe('john.smith@example.org'); - element('.doc-example-live li:first a:contains("clear")').click(); - expect(element('.doc-example-live li:first input').val()).toBe(''); + element('#ctrl-exmpl li:first a:contains("clear")').click(); + expect(element('#ctrl-exmpl li:first input').val()).toBe(''); - element('.doc-example-live li:last a:contains("add")').click(); - expect(element('.doc-example-live li:nth-child(3) input').val()) + element('#ctrl-exmpl li:last a:contains("add")').click(); + expect(element('#ctrl-exmpl li:nth-child(3) input').val()) .toBe('yourname@example.org'); }); + */ var ngControllerDirective = [function() { return { @@ -12976,13 +15384,13 @@ var ngCspDirective = ['$sniffer', function($sniffer) { */ var ngEventDirectives = {}; forEach( - 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave'.split(' '), + 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur'.split(' '), function(name) { var directiveName = directiveNormalize('ng-' + name); ngEventDirectives[directiveName] = ['$parse', function($parse) { return function(scope, element, attr) { var fn = $parse(attr[directiveName]); - element.bind(lowercase(name), function(event) { + element.on(lowercase(name), function(event) { scope.$apply(function() { fn(scope, {$event:event}); }); @@ -13103,6 +15511,54 @@ forEach( */ +/** + * @ngdoc directive + * @name ng.directive:ngKeydown + * + * @description + * Specify custom behavior on keydown event. + * + * @element ANY + * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon + * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + + +/** + * @ngdoc directive + * @name ng.directive:ngKeyup + * + * @description + * Specify custom behavior on keyup event. + * + * @element ANY + * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon + * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + + +/** + * @ngdoc directive + * @name ng.directive:ngKeypress + * + * @description + * Specify custom behavior on keypress event. + * + * @element ANY + * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon + * keypress. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + + /** * @ngdoc directive * @name ng.directive:ngSubmit @@ -13111,10 +15567,11 @@ forEach( * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the - * server and reloading the current page). + * server and reloading the current page) **but only if the form does not contain an `action` + * attribute**. * * @element form - * @param {expression} ngSubmit {@link guide/expression Expression} to eval. + * @param {expression} ngSubmit {@link guide/expression Expression} to eval. (Event object is available as `$event`) * * @example @@ -13154,11 +15611,144 @@ forEach( */ -var ngSubmitDirective = ngDirective(function(scope, element, attrs) { - element.bind('submit', function() { - scope.$apply(attrs.ngSubmit); - }); -}); + +/** + * @ngdoc directive + * @name ng.directive:ngFocus + * + * @description + * Specify custom behavior on focus event. + * + * @element window, input, select, textarea, a + * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon + * focus. (Event object is available as `$event`) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + +/** + * @ngdoc directive + * @name ng.directive:ngBlur + * + * @description + * Specify custom behavior on blur event. + * + * @element window, input, select, textarea, a + * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon + * blur. (Event object is available as `$event`) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + +/** + * @ngdoc directive + * @name ng.directive:ngIf + * @restrict A + * + * @description + * The `ngIf` directive removes and recreates a portion of the DOM tree (HTML) + * conditionally based on **"falsy"** and **"truthy"** values, respectively, evaluated within + * an {expression}. In other words, if the expression assigned to **ngIf evaluates to a false + * value** then **the element is removed from the DOM** and **if true** then **a clone of the + * element is reinserted into the DOM**. + * + * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the + * element in the DOM rather than changing its visibility via the `display` css property. A common + * case when this difference is significant is when using css selectors that rely on an element's + * position within the DOM (HTML), such as the `:first-child` or `:last-child` pseudo-classes. + * + * Note that **when an element is removed using ngIf its scope is destroyed** and **a new scope + * is created when the element is restored**. The scope created within `ngIf` inherits from + * its parent scope using + * {@link https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance prototypal inheritance}. + * An important implication of this is if `ngModel` is used within `ngIf` to bind to + * a javascript primitive defined in the parent scope. In this case any modifications made to the + * variable within the child scope will override (hide) the value in the parent scope. + * + * Also, `ngIf` recreates elements using their compiled state. An example scenario of this behavior + * is if an element's class attribute is directly modified after it's compiled, using something like + * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element + * the added class will be lost because the original compiled state is used to regenerate the element. + * + * Additionally, you can provide animations via the ngAnimate module to animate the **enter** + * and **leave** effects. + * + * @animations + * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container + * leave - happens just before the ngIf contents are removed from the DOM + * + * @element ANY + * @scope + * @param {expression} ngIf If the {@link guide/expression expression} is falsy then + * the element is removed from the DOM tree (HTML). + * + * @example + + + Click me:
+ Show when checked: + + I'm removed when the checkbox is unchecked. + +
+ + .animate-if { + background:white; + border:1px solid black; + padding:10px; + } + + .animate-if.ng-enter, .animate-if.ng-leave { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + } + + .animate-if.ng-enter, + .animate-if.ng-leave.ng-leave-active { + opacity:0; + } + + .animate-if.ng-enter.ng-enter-active, + .animate-if.ng-leave { + opacity:1; + } + +
+ */ +var ngIfDirective = ['$animate', function($animate) { + return { + transclude: 'element', + priority: 1000, + terminal: true, + restrict: 'A', + compile: function (element, attr, transclude) { + return function ($scope, $element, $attr) { + var childElement, childScope; + $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { + if (childElement) { + $animate.leave(childElement); + childElement = undefined; + } + if (childScope) { + childScope.$destroy(); + childScope = undefined; + } + if (toBoolean(value)) { + childScope = $scope.$new(); + transclude(childScope, function (clone) { + childElement = clone; + $animate.enter(clone, $element.parent(), $element); + }); + } + }); + } + } + } +}]; /** * @ngdoc directive @@ -13168,9 +15758,26 @@ var ngSubmitDirective = ngDirective(function(scope, element, attrs) { * @description * Fetches, compiles and includes an external HTML fragment. * - * Keep in mind that Same Origin Policy applies to included resources - * (e.g. ngInclude won't work for cross-domain requests on all browsers and for - * file:// access on some browsers). + * Keep in mind that: + * + * - by default, the template URL is restricted to the same domain and protocol as the + * application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl + * $sce.getTrustedResourceUrl} on it. To load templates from other domains and/or protocols, + * you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or + * {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. Refer Angular's {@link + * ng.$sce Strict Contextual Escaping}. + * - in addition, the browser's + * {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest + * Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing + * (CORS)} policy apply that may further restrict whether the template is successfully loaded. + * (e.g. ngInclude won't work for cross-domain requests on all browsers and for `file://` + * access on some browsers) + * + * @animations + * enter - animation is used to bring new content into the browser. + * leave - animation is used to animate existing content away. + * + * The enter and leave animation occur concurrently. * * @scope * @@ -13186,7 +15793,7 @@ var ngSubmitDirective = ngDirective(function(scope, element, attrs) { * - Otherwise enable scrolling only if the expression evaluates to truthy value. * * @example - +
url of the template: {{template.url}}
-
+
+
+
@@ -13211,6 +15820,48 @@ var ngSubmitDirective = ngDirective(function(scope, element, attrs) { Content of template2.html + + .example-animate-container { + position:relative; + background:white; + border:1px solid black; + height:40px; + overflow:hidden; + } + + .example-animate-container > div { + padding:10px; + } + + .include-example.ng-enter, .include-example.ng-leave { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + + position:absolute; + top:0; + left:0; + right:0; + bottom:0; + display:block; + padding:10px; + } + + .include-example.ng-enter { + top:-50px; + } + .include-example.ng-enter.ng-enter-active { + top:0; + } + + .include-example.ng-leave { + top:0; + } + .include-example.ng-leave.ng-leave-active { + top:50px; + } + it('should load template1.html', function() { expect(element('.doc-example-live [ng-include]').text()). @@ -13223,13 +15874,23 @@ var ngSubmitDirective = ngDirective(function(scope, element, attrs) { }); it('should change to blank', function() { select('template').option(''); - expect(element('.doc-example-live [ng-include]').text()).toEqual(''); + expect(element('.doc-example-live [ng-include]')).toBe(undefined); });
*/ +/** + * @ngdoc event + * @name ng.directive:ngInclude#$includeContentRequested + * @eventOf ng.directive:ngInclude + * @eventType emit on the scope ngInclude was declared in + * @description + * Emitted every time the ngInclude content is requested. + */ + + /** * @ngdoc event * @name ng.directive:ngInclude#$includeContentLoaded @@ -13238,52 +15899,68 @@ var ngSubmitDirective = ngDirective(function(scope, element, attrs) { * @description * Emitted every time the ngInclude content is reloaded. */ -var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', - function($http, $templateCache, $anchorScroll, $compile) { +var NG_INCLUDE_PRIORITY = 500; +var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', '$animate', '$sce', + function($http, $templateCache, $anchorScroll, $compile, $animate, $sce) { return { restrict: 'ECA', terminal: true, + priority: NG_INCLUDE_PRIORITY, compile: function(element, attr) { var srcExp = attr.ngInclude || attr.src, onloadExp = attr.onload || '', autoScrollExp = attr.autoscroll; - return function(scope, element) { + element.html(''); + var anchor = jqLite(document.createComment(' ngInclude: ' + srcExp + ' ')); + element.replaceWith(anchor); + + return function(scope) { var changeCounter = 0, - childScope; + currentScope, + currentElement; - var clearContent = function() { - if (childScope) { - childScope.$destroy(); - childScope = null; + var cleanupLastIncludeContent = function() { + if (currentScope) { + currentScope.$destroy(); + currentScope = null; + } + if(currentElement) { + $animate.leave(currentElement); + currentElement = null; } - - element.html(''); }; - scope.$watch(srcExp, function ngIncludeWatchAction(src) { + scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) { var thisChangeId = ++changeCounter; if (src) { $http.get(src, {cache: $templateCache}).success(function(response) { if (thisChangeId !== changeCounter) return; + var newScope = scope.$new(); + + cleanupLastIncludeContent(); - if (childScope) childScope.$destroy(); - childScope = scope.$new(); + currentScope = newScope; + currentElement = element.clone(); + currentElement.html(response); + $animate.enter(currentElement, null, anchor); - element.html(response); - $compile(element.contents())(childScope); + $compile(currentElement, false, NG_INCLUDE_PRIORITY - 1)(currentScope); if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } - childScope.$emit('$includeContentLoaded'); + currentScope.$emit('$includeContentLoaded'); scope.$eval(onloadExp); }).error(function() { - if (thisChangeId === changeCounter) clearContent(); + if (thisChangeId === changeCounter) cleanupLastIncludeContent(); }); - } else clearContent(); + scope.$emit('$includeContentRequested'); + } else { + cleanupLastIncludeContent(); + } }); }; } @@ -13366,7 +16043,7 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); * @description * # Overview * `ngPluralize` is a directive that displays messages according to en-US localization rules. - * These rules are bundled with angular.js and the rules can be overridden + * These rules are bundled with angular.js, but can be overridden * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive * by specifying the mappings between * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html @@ -13377,10 +16054,10 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} in Angular's default en-US locale: "one" and "other". * - * While a pural category may match many numbers (for example, in en-US locale, "other" can match + * While a plural category may match many numbers (for example, in en-US locale, "other" can match * any number that is not 1), an explicit number rule can only match one number. For example, the - * explicit number rule for "3" matches the number 3. You will see the use of plural categories - * and explicit number rules throughout later parts of this documentation. + * explicit number rule for "3" matches the number 3. There are examples of plural categories + * and explicit number rules throughout the rest of this documentation. * * # Configuring ngPluralize * You configure ngPluralize by providing 2 attributes: `count` and `when`. @@ -13390,8 +16067,7 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); * Angular expression}; these are evaluated on the current scope for its bound value. * * The `when` attribute specifies the mappings between plural categories and the actual - * string to be displayed. The value of the attribute should be a JSON object so that Angular - * can interpret it correctly. + * string to be displayed. The value of the attribute should be a JSON object. * * The following example shows how to configure ngPluralize: * @@ -13445,7 +16121,7 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); * plural categories "one" and "other". * * @param {string|expression} count The variable to be bounded to. - * @param {string} when The mapping between plural category to its correspoding strings. + * @param {string} when The mapping between plural category to its corresponding strings. * @param {number=} offset Offset to deduct from the total number. * * @example @@ -13533,13 +16209,20 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp restrict: 'EA', link: function(scope, element, attr) { var numberExp = attr.count, - whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs + whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs offset = attr.offset || 0, - whens = scope.$eval(whenExp), + whens = scope.$eval(whenExp) || {}, whensExpFns = {}, startSymbol = $interpolate.startSymbol(), - endSymbol = $interpolate.endSymbol(); + endSymbol = $interpolate.endSymbol(), + isWhen = /^when(Minus)?(.+)$/; + forEach(attr, function(expression, attributeName) { + if (isWhen.test(attributeName)) { + whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] = + element.attr(attr.$attr[attributeName]); + } + }); forEach(whens, function(expression, key) { whensExpFns[key] = $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' + @@ -13575,203 +16258,514 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp * * Special properties are exposed on the local scope of each template instance, including: * - * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1) - * * `$first` – `{boolean}` – true if the repeated element is first in the iterator. - * * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator. - * * `$last` – `{boolean}` – true if the repeated element is last in the iterator. + * | Variable | Type | Details | + * |-----------|-----------------|-----------------------------------------------------------------------------| + * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) | + * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. | + * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. | + * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. | + * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). | + * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). | + * + * + * # Special repeat start and end points + * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending + * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively. + * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on) + * up to and including the ending HTML tag where **ng-repeat-end** is placed. * + * The example below makes use of this feature: + *
+ *   
+ * Header {{ item }} + *
+ *
+ * Body {{ item }} + *
+ *
+ * Footer {{ item }} + *
+ *
+ * + * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to: + *
+ *   
+ * Header A + *
+ *
+ * Body A + *
+ *
+ * Footer A + *
+ *
+ * Header B + *
+ *
+ * Body B + *
+ *
+ * Footer B + *
+ *
+ * + * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such + * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**). + * + * @animations + * enter - when a new item is added to the list or when an item is revealed after a filter + * leave - when an item is removed from the list or when an item is filtered out + * move - when an adjacent item is filtered out causing a reorder or when the item contents are reordered * * @element ANY * @scope * @priority 1000 - * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two + * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * - * For example: `track in cd.tracks`. + * For example: `album in artist.albums`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * + * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function + * which can be used to associate the objects in the collection with the DOM elements. If no tracking function + * is specified the ng-repeat associates elements by identity in the collection. It is an error to have + * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are + * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression, + * before specifying a tracking expression. + * + * For example: `item in items` is equivalent to `item in items track by $id(item)'. This implies that the DOM elements + * will be associated by item identity in the array. + * + * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique + * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements + * with the corresponding item in the array by identity. Moving the same object in array would move the DOM + * element in the same way ian the DOM. + * + * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this + * case the object identity does not matter. Two objects are considered equivalent as long as their `id` + * property is same. + * + * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter + * to items in conjunction with a tracking expression. + * * @example * This example initializes the scope to a list of names and * then uses `ngRepeat` to display every person: - - -
- I have {{friends.length}} friends. They are: -
    -
  • - [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. -
  • -
-
-
- - it('should check ng-repeat', function() { - var r = using('.doc-example-live').repeater('ul li'); - expect(r.count()).toBe(2); - expect(r.row(0)).toEqual(["1","John","25"]); - expect(r.row(1)).toEqual(["2","Mary","28"]); - }); - -
+ + +
+ I have {{friends.length}} friends. They are: + +
    +
  • + [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. +
  • +
+
+
+ + .example-animate-container { + background:white; + border:1px solid black; + list-style:none; + margin:0; + padding:0; + } + + .example-animate-container > li { + padding:10px; + list-style:none; + } + + .animate-repeat.ng-enter, + .animate-repeat.ng-leave, + .animate-repeat.ng-move { + -webkit-transition:all linear 0.5s; + -moz-transition:all linear 0.5s; + -o-transition:all linear 0.5s; + transition:all linear 0.5s; + } + + .animate-repeat.ng-enter { + line-height:0; + opacity:0; + padding-top:0; + padding-bottom:0; + } + .animate-repeat.ng-enter.ng-enter-active { + line-height:20px; + opacity:1; + padding:10px; + } + + .animate-repeat.ng-leave { + opacity:1; + line-height:20px; + padding:10px; + } + .animate-repeat.ng-leave.ng-leave-active { + opacity:0; + line-height:0; + padding-top:0; + padding-bottom:0; + } + + .animate-repeat.ng-move { } + .animate-repeat.ng-move.ng-move-active { } + + + it('should render initial data set', function() { + var r = using('.doc-example-live').repeater('ul li'); + expect(r.count()).toBe(10); + expect(r.row(0)).toEqual(["1","John","25"]); + expect(r.row(1)).toEqual(["2","Jessie","30"]); + expect(r.row(9)).toEqual(["10","Samantha","60"]); + expect(binding('friends.length')).toBe("10"); + }); + + it('should update repeater when filter predicate changes', function() { + var r = using('.doc-example-live').repeater('ul li'); + expect(r.count()).toBe(10); + + input('q').enter('ma'); + + expect(r.count()).toBe(2); + expect(r.row(0)).toEqual(["1","Mary","28"]); + expect(r.row(1)).toEqual(["2","Samantha","60"]); + }); + +
*/ -var ngRepeatDirective = ngDirective({ - transclude: 'element', - priority: 1000, - terminal: true, - compile: function(element, attr, linker) { - return function(scope, iterStartElement, attr){ - var expression = attr.ngRepeat; - var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/), - lhs, rhs, valueIdent, keyIdent; - if (! match) { - throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" + - expression + "'."); - } - lhs = match[1]; - rhs = match[2]; - match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); - if (!match) { - throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" + - lhs + "'."); - } - valueIdent = match[3] || match[1]; - keyIdent = match[2]; - - // Store a list of elements from previous run. This is a hash where key is the item from the - // iterator, and the value is an array of objects with following properties. - // - scope: bound scope - // - element: previous element. - // - index: position - // We need an array of these objects since the same object can be returned from the iterator. - // We expect this to be a rare case. - var lastOrder = new HashQueueMap(); - - scope.$watch(function ngRepeatWatch(scope){ - var index, length, - collection = scope.$eval(rhs), - cursor = iterStartElement, // current position of the node - // Same as lastOrder but it has the current state. It will become the - // lastOrder on the next iteration. - nextOrder = new HashQueueMap(), - arrayBound, - childScope, - key, value, // key/value of iteration - array, - last; // last object information {scope, element, index} - - - - if (!isArray(collection)) { - // if object, extract keys, sort them and use to determine order of iteration over obj props - array = []; - for(key in collection) { - if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { - array.push(key); - } - } - array.sort(); +var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { + var NG_REMOVED = '$$NG_REMOVED'; + var ngRepeatMinErr = minErr('ngRepeat'); + return { + transclude: 'element', + priority: 1000, + terminal: true, + compile: function(element, attr, linker) { + return function($scope, $element, $attr){ + var expression = $attr.ngRepeat; + var match = expression.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/), + trackByExp, trackByExpGetter, trackByIdFn, trackByIdArrayFn, trackByIdObjFn, lhs, rhs, valueIdentifier, keyIdentifier, + hashFnLocals = {$id: hashKey}; + + if (!match) { + throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", + expression); + } + + lhs = match[1]; + rhs = match[2]; + trackByExp = match[4]; + + if (trackByExp) { + trackByExpGetter = $parse(trackByExp); + trackByIdFn = function(key, value, index) { + // assign key, value, and $index to the locals so that they can be used in hash functions + if (keyIdentifier) hashFnLocals[keyIdentifier] = key; + hashFnLocals[valueIdentifier] = value; + hashFnLocals.$index = index; + return trackByExpGetter($scope, hashFnLocals); + }; } else { - array = collection || []; + trackByIdArrayFn = function(key, value) { + return hashKey(value); + } + trackByIdObjFn = function(key) { + return key; + } + } + + match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); + if (!match) { + throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.", + lhs); } + valueIdentifier = match[3] || match[1]; + keyIdentifier = match[2]; + + // Store a list of elements from previous run. This is a hash where key is the item from the + // iterator, and the value is objects with following properties. + // - scope: bound scope + // - element: previous element. + // - index: position + var lastBlockMap = {}; + + //watch props + $scope.$watchCollection(rhs, function ngRepeatAction(collection){ + var index, length, + previousNode = $element[0], // current position of the node + nextNode, + // Same as lastBlockMap but it has the current state. It will become the + // lastBlockMap on the next iteration. + nextBlockMap = {}, + arrayLength, + childScope, + key, value, // key/value of iteration + trackById, + collectionKeys, + block, // last object information {scope, element, id} + nextBlockOrder = []; + + + if (isArrayLike(collection)) { + collectionKeys = collection; + trackByIdFn = trackByIdFn || trackByIdArrayFn; + } else { + trackByIdFn = trackByIdFn || trackByIdObjFn; + // if object, extract keys, sort them and use to determine order of iteration over obj props + collectionKeys = []; + for (key in collection) { + if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { + collectionKeys.push(key); + } + } + collectionKeys.sort(); + } + + arrayLength = collectionKeys.length; + + // locate existing items + length = nextBlockOrder.length = collectionKeys.length; + for(index = 0; index < length; index++) { + key = (collection === collectionKeys) ? index : collectionKeys[index]; + value = collection[key]; + trackById = trackByIdFn(key, value, index); + if(lastBlockMap.hasOwnProperty(trackById)) { + block = lastBlockMap[trackById] + delete lastBlockMap[trackById]; + nextBlockMap[trackById] = block; + nextBlockOrder[index] = block; + } else if (nextBlockMap.hasOwnProperty(trackById)) { + // restore lastBlockMap + forEach(nextBlockOrder, function(block) { + if (block && block.startNode) lastBlockMap[block.id] = block; + }); + // This is a duplicate and we need to throw an error + throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}", + expression, trackById); + } else { + // new never before seen block + nextBlockOrder[index] = { id: trackById }; + nextBlockMap[trackById] = false; + } + } - arrayBound = array.length-1; + // remove existing items + for (key in lastBlockMap) { + if (lastBlockMap.hasOwnProperty(key)) { + block = lastBlockMap[key]; + $animate.leave(block.elements); + forEach(block.elements, function(element) { element[NG_REMOVED] = true}); + block.scope.$destroy(); + } + } - // we are not using forEach for perf reasons (trying to avoid #call) - for (index = 0, length = array.length; index < length; index++) { - key = (collection === array) ? index : array[index]; - value = collection[key]; + // we are not using forEach for perf reasons (trying to avoid #call) + for (index = 0, length = collectionKeys.length; index < length; index++) { + key = (collection === collectionKeys) ? index : collectionKeys[index]; + value = collection[key]; + block = nextBlockOrder[index]; - last = lastOrder.shift(value); + if (block.startNode) { + // if we have already seen this object, then we need to reuse the + // associated scope/element + childScope = block.scope; - if (last) { - // if we have already seen this object, then we need to reuse the - // associated scope/element - childScope = last.scope; - nextOrder.push(value, last); + nextNode = previousNode; + do { + nextNode = nextNode.nextSibling; + } while(nextNode && nextNode[NG_REMOVED]); - if (index === last.index) { - // do nothing - cursor = last.element; + if (block.startNode == nextNode) { + // do nothing + } else { + // existing item which got moved + $animate.move(block.elements, null, jqLite(previousNode)); + } + previousNode = block.endNode; } else { - // existing item which got moved - last.index = index; - // This may be a noop, if the element is next, but I don't know of a good way to - // figure this out, since it would require extra DOM access, so let's just hope that - // the browsers realizes that it is noop, and treats it as such. - cursor.after(last.element); - cursor = last.element; + // new item which we don't know about + childScope = $scope.$new(); } - } else { - // new item which we don't know about - childScope = scope.$new(); - } - - childScope[valueIdent] = value; - if (keyIdent) childScope[keyIdent] = key; - childScope.$index = index; - - childScope.$first = (index === 0); - childScope.$last = (index === arrayBound); - childScope.$middle = !(childScope.$first || childScope.$last); - - if (!last) { - linker(childScope, function(clone){ - cursor.after(clone); - last = { - scope: childScope, - element: (cursor = clone), - index: index - }; - nextOrder.push(value, last); - }); - } - } - //shrink children - for (key in lastOrder) { - if (lastOrder.hasOwnProperty(key)) { - array = lastOrder[key]; - while(array.length) { - value = array.pop(); - value.element.remove(); - value.scope.$destroy(); + childScope[valueIdentifier] = value; + if (keyIdentifier) childScope[keyIdentifier] = key; + childScope.$index = index; + childScope.$first = (index === 0); + childScope.$last = (index === (arrayLength - 1)); + childScope.$middle = !(childScope.$first || childScope.$last); + childScope.$odd = !(childScope.$even = index%2==0); + + if (!block.startNode) { + linker(childScope, function(clone) { + $animate.enter(clone, null, jqLite(previousNode)); + previousNode = clone; + block.scope = childScope; + block.startNode = clone[0]; + block.elements = clone; + block.endNode = clone[clone.length - 1]; + nextBlockMap[block.id] = block; + }); } } - } - - lastOrder = nextOrder; - }); - }; - } -}); + lastBlockMap = nextBlockMap; + }); + }; + } + }; +}]; /** * @ngdoc directive * @name ng.directive:ngShow * * @description - * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML) - * conditionally. + * The `ngShow` directive shows and hides the given HTML element conditionally based on the expression + * provided to the ngShow attribute. The show and hide mechanism is a achieved by removing and adding + * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is a predefined CSS class present + * in AngularJS which sets the display style to none (using an !important flag). + * + *
+ * 
+ * 
+ * + * + *
+ *
+ * + * When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute + * on the element causing it to become hidden. When true, the ng-hide CSS class is removed + * from the element causing the element not to appear hidden. + * + * ## Why is !important used? + * + * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector + * can be easily overridden by heavier selectors. For example, something as simple + * as changing the display style on a HTML list item would make hidden elements appear visible. + * This also becomes a bigger issue when dealing with CSS frameworks. + * + * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector + * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the + * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. + * + * ### Overriding .ng-hide + * + * If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by + * restating the styles for the .ng-hide class in CSS: + *
+ * .ng-hide {
+ *   //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
+ *   display:block!important;
+ *
+ *   //this is just another form of hiding an element
+ *   position:absolute;
+ *   top:-9999px;
+ *   left:-9999px;
+ * }
+ * 
+ * + * Just remember to include the important flag so the CSS override will function. + * + * ## A note about animations with ngShow + * + * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression + * is true and false. This system works similar to the animation system present with ngClass, however, the + * only difference is that you must also include the !important flag to override the display property so + * that you can perform an animation when the element is hidden during the time of the animation. + * + *
+ * //
+ * //a working example can be found at the bottom of this page
+ * //
+ * .my-element.ng-hide-add, .my-element.ng-hide-remove {
+ *   transition:0.5s linear all;
+ *   display:block!important;
+ * }
+ *
+ * .my-element.ng-hide-add { ... }
+ * .my-element.ng-hide-add.ng-hide-add-active { ... }
+ * .my-element.ng-hide-remove { ... }
+ * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
+ * 
+ * + * @animations + * addClass: .ng-hide - happens after the ngShow expression evaluates to a truthy value and the just before contents are set to visible + * removeClass: .ng-hide - happens after the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden * * @element ANY * @param {expression} ngShow If the {@link guide/expression expression} is truthy * then the element is shown or hidden respectively. * * @example - - - Click me:
- Show: I show up when your checkbox is checked.
- Hide: I hide when your checkbox is checked. -
- + + + Click me:
+
+ Show: +
+ I show up when your checkbox is checked. +
+
+
+ Hide: +
+ I hide when your checkbox is checked. +
+
+
+ + .animate-show.ng-hide-add, + .animate-show.ng-hide-remove { + -webkit-transition:all linear 0.5s; + -moz-transition:all linear 0.5s; + -o-transition:all linear 0.5s; + transition:all linear 0.5s; + display:block!important; + } + + .animate-show.ng-hide-add.ng-hide-add-active, + .animate-show.ng-hide-remove { + line-height:0; + opacity:0; + padding:0 10px; + } + + .animate-show.ng-hide-add, + .animate-show.ng-hide-remove.ng-hide-remove-active { + line-height:20px; + opacity:1; + padding:10px; + border:1px solid black; + background:white; + } + + .check-element { + padding:10px; + border:1px solid black; + background:white; + } + + it('should check ng-show / ng-hide', function() { expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); @@ -13781,15 +16775,16 @@ var ngRepeatDirective = ngDirective({ expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); -
-
+ +
*/ -//TODO(misko): refactor to remove element from the DOM -var ngShowDirective = ngDirective(function(scope, element, attr){ - scope.$watch(attr.ngShow, function ngShowWatchAction(value){ - element.css('display', toBoolean(value) ? '' : 'none'); - }); -}); +var ngShowDirective = ['$animate', function($animate) { + return function(scope, element, attr) { + scope.$watch(attr.ngShow, function ngShowWatchAction(value){ + $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide'); + }); + }; +}]; /** @@ -13797,39 +16792,151 @@ var ngShowDirective = ngDirective(function(scope, element, attr){ * @name ng.directive:ngHide * * @description - * The `ngHide` and `ngShow` directives hide or show a portion of the DOM tree (HTML) - * conditionally. + * The `ngHide` directive shows and hides the given HTML element conditionally based on the expression + * provided to the ngHide attribute. The show and hide mechanism is a achieved by removing and adding + * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is a predefined CSS class present + * in AngularJS which sets the display style to none (using an !important flag). + * + *
+ * 
+ * 
+ * + * + *
+ *
+ * + * When the ngHide expression evaluates to true then the .ng-hide CSS class is added to the class attribute + * on the element causing it to become hidden. When false, the ng-hide CSS class is removed + * from the element causing the element not to appear hidden. + * + * ## Why is !important used? + * + * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector + * can be easily overridden by heavier selectors. For example, something as simple + * as changing the display style on a HTML list item would make hidden elements appear visible. + * This also becomes a bigger issue when dealing with CSS frameworks. + * + * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector + * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the + * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. + * + * ### Overriding .ng-hide + * + * If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by + * restating the styles for the .ng-hide class in CSS: + *
+ * .ng-hide {
+ *   //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
+ *   display:block!important;
+ *
+ *   //this is just another form of hiding an element
+ *   position:absolute;
+ *   top:-9999px;
+ *   left:-9999px;
+ * }
+ * 
+ * + * Just remember to include the important flag so the CSS override will function. + * + * ## A note about animations with ngHide + * + * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression + * is true and false. This system works similar to the animation system present with ngClass, however, the + * only difference is that you must also include the !important flag to override the display property so + * that you can perform an animation when the element is hidden during the time of the animation. + * + *
+ * //
+ * //a working example can be found at the bottom of this page
+ * //
+ * .my-element.ng-hide-add, .my-element.ng-hide-remove {
+ *   transition:0.5s linear all;
+ *   display:block!important;
+ * }
+ *
+ * .my-element.ng-hide-add { ... }
+ * .my-element.ng-hide-add.ng-hide-add-active { ... }
+ * .my-element.ng-hide-remove { ... }
+ * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
+ * 
+ * + * @animations + * removeClass: .ng-hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden + * addClass: .ng-hide - happens after the ngHide expression evaluates to a non truthy value and just before the contents are set to visible * * @element ANY * @param {expression} ngHide If the {@link guide/expression expression} is truthy then * the element is shown or hidden respectively. * * @example - - - Click me:
- Show: I show up when you checkbox is checked?
- Hide: I hide when you checkbox is checked? -
- + + + Click me:
+
+ Show: +
+ I show up when your checkbox is checked. +
+
+
+ Hide: +
+ I hide when your checkbox is checked. +
+
+
+ + .animate-hide.ng-hide-add, + .animate-hide.ng-hide-remove { + -webkit-transition:all linear 0.5s; + -moz-transition:all linear 0.5s; + -o-transition:all linear 0.5s; + transition:all linear 0.5s; + display:block!important; + } + + .animate-hide.ng-hide-add.ng-hide-add-active, + .animate-hide.ng-hide-remove { + line-height:0; + opacity:0; + padding:0 10px; + } + + .animate-hide.ng-hide-add, + .animate-hide.ng-hide-remove.ng-hide-remove-active { + line-height:20px; + opacity:1; + padding:10px; + border:1px solid black; + background:white; + } + + .check-element { + padding:10px; + border:1px solid black; + background:white; + } + + it('should check ng-show / ng-hide', function() { - expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); - expect(element('.doc-example-live span:last:visible').count()).toEqual(1); + expect(element('.doc-example-live .check-element:first:hidden').count()).toEqual(1); + expect(element('.doc-example-live .check-element:last:visible').count()).toEqual(1); input('checked').check(); - expect(element('.doc-example-live span:first:visible').count()).toEqual(1); - expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); + expect(element('.doc-example-live .check-element:first:visible').count()).toEqual(1); + expect(element('.doc-example-live .check-element:last:hidden').count()).toEqual(1); }); -
-
+ + */ -//TODO(misko): refactor to remove element from the DOM -var ngHideDirective = ngDirective(function(scope, element, attr){ - scope.$watch(attr.ngHide, function ngHideWatchAction(value){ - element.css('display', toBoolean(value) ? 'none' : ''); - }); -}); +var ngHideDirective = ['$animate', function($animate) { + return function(scope, element, attr) { + scope.$watch(attr.ngHide, function ngHideWatchAction(value){ + $animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide'); + }); + }; +}]; /** * @ngdoc directive @@ -13883,92 +16990,162 @@ var ngStyleDirective = ngDirective(function(scope, element, attr) { * @restrict EA * * @description - * Conditionally change the DOM structure. + * The ngSwitch directive is used to conditionally swap DOM structure on your template based on a scope expression. + * Elements within ngSwitch but without ngSwitchWhen or ngSwitchDefault directives will be preserved at the location + * as specified in the template. + * + * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it + * from the template cache), ngSwitch simply choses one of the nested elements and makes it visible based on which element + * matches the value obtained from the evaluated expression. In other words, you define a container element + * (where you place the directive), place an expression on the **on="..." attribute** + * (or the **ng-switch="..." attribute**), define any inner elements inside of the directive and place + * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on + * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default + * attribute is displayed. + * + * @animations + * enter - happens after the ngSwtich contents change and the matched child element is placed inside the container + * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM * * @usage * * ... * ... - * ... * ... * * * @scope * @param {*} ngSwitch|on expression to match against ng-switch-when. * @paramDescription - * On child elments add: + * On child elements add: * * * `ngSwitchWhen`: the case statement to match against. If match then this - * case will be displayed. - * * `ngSwitchDefault`: the default case when no other casses match. + * case will be displayed. If the same match appears multiple times, all the + * elements will be displayed. + * * `ngSwitchDefault`: the default case when no other case match. If there + * are multiple default cases, all of them will be displayed when no other + * case match. + * * * @example - - - -
- - selection={{selection}} -
-
+ + +
+ + selection={{selection}} +
+
Settings Div
- Home Span - default -
+
Home Span
+
default
- - - it('should start in settings', function() { - expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/); - }); - it('should change to home', function() { - select('selection').option('home'); - expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/); - }); - it('should select deafault', function() { - select('selection').option('other'); - expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/); - }); - - - */ -var NG_SWITCH = 'ng-switch'; -var ngSwitchDirective = valueFn({ - restrict: 'EA', - require: 'ngSwitch', - // asks for $scope to fool the BC controller module - controller: ['$scope', function ngSwitchController() { - this.cases = {}; - }], - link: function(scope, element, attr, ctrl) { - var watchExpr = attr.ngSwitch || attr.on, - selectedTransclude, - selectedElement, - selectedScope; - - scope.$watch(watchExpr, function ngSwitchWatchAction(value) { - if (selectedElement) { - selectedScope.$destroy(); - selectedElement.remove(); - selectedElement = selectedScope = null; - } - if ((selectedTransclude = ctrl.cases['!' + value] || ctrl.cases['?'])) { - scope.$eval(attr.change); - selectedScope = scope.$new(); - selectedTransclude(selectedScope, function(caseElement) { - selectedElement = caseElement; - element.append(caseElement); - }); +
+ + + function Ctrl($scope) { + $scope.items = ['settings', 'home', 'other']; + $scope.selection = $scope.items[0]; } - }); + + + .animate-switch-container { + position:relative; + background:white; + border:1px solid black; + height:40px; + overflow:hidden; + } + + .animate-switch-container > div { + padding:10px; + } + + .animate-switch-container > .ng-enter, + .animate-switch-container > .ng-leave { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + + position:absolute; + top:0; + left:0; + right:0; + bottom:0; + } + + .animate-switch-container > .ng-enter { + top:-50px; + } + .animate-switch-container > .ng-enter.ng-enter-active { + top:0; + } + + .animate-switch-container > .ng-leave { + top:0; + } + .animate-switch-container > .ng-leave.ng-leave-active { + top:50px; + } + + + it('should start in settings', function() { + expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/); + }); + it('should change to home', function() { + select('selection').option('home'); + expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/); + }); + it('should select default', function() { + select('selection').option('other'); + expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/); + }); + + + */ +var ngSwitchDirective = ['$animate', function($animate) { + return { + restrict: 'EA', + require: 'ngSwitch', + + // asks for $scope to fool the BC controller module + controller: ['$scope', function ngSwitchController() { + this.cases = {}; + }], + link: function(scope, element, attr, ngSwitchController) { + var watchExpr = attr.ngSwitch || attr.on, + selectedTranscludes, + selectedElements, + selectedScopes = []; + + scope.$watch(watchExpr, function ngSwitchWatchAction(value) { + for (var i= 0, ii=selectedScopes.length; i' + '
{{title}}
' + '
' + @@ -14042,177 +17220,18 @@ var ngSwitchDefaultDirective = ngDirective({ * */ var ngTranscludeDirective = ngDirective({ - controller: ['$transclude', '$element', function($transclude, $element) { - $transclude(function(clone) { - $element.append(clone); + controller: ['$transclude', '$element', '$scope', function($transclude, $element, $scope) { + // use evalAsync so that we don't process transclusion before directives on the parent element even when the + // transclusion replaces the current element. (we can't use priority here because that applies only to compile fns + // and not controllers + $scope.$evalAsync(function() { + $transclude(function(clone) { + $element.append(clone); + }); }); }] }); -/** - * @ngdoc directive - * @name ng.directive:ngView - * @restrict ECA - * - * @description - * # Overview - * `ngView` is a directive that complements the {@link ng.$route $route} service by - * including the rendered template of the current route into the main layout (`index.html`) file. - * Every time the current route changes, the included view changes with it according to the - * configuration of the `$route` service. - * - * @scope - * @example - - -
- Choose: - Moby | - Moby: Ch1 | - Gatsby | - Gatsby: Ch4 | - Scarlet Letter
- -
-
- -
$location.path() = {{$location.path()}}
-
$route.current.templateUrl = {{$route.current.templateUrl}}
-
$route.current.params = {{$route.current.params}}
-
$route.current.scope.name = {{$route.current.scope.name}}
-
$routeParams = {{$routeParams}}
-
-
- - - controller: {{name}}
- Book Id: {{params.bookId}}
-
- - - controller: {{name}}
- Book Id: {{params.bookId}}
- Chapter Id: {{params.chapterId}} -
- - - angular.module('ngView', [], function($routeProvider, $locationProvider) { - $routeProvider.when('/Book/:bookId', { - templateUrl: 'book.html', - controller: BookCntl - }); - $routeProvider.when('/Book/:bookId/ch/:chapterId', { - templateUrl: 'chapter.html', - controller: ChapterCntl - }); - - // configure html5 to get links working on jsfiddle - $locationProvider.html5Mode(true); - }); - - function MainCntl($scope, $route, $routeParams, $location) { - $scope.$route = $route; - $scope.$location = $location; - $scope.$routeParams = $routeParams; - } - - function BookCntl($scope, $routeParams) { - $scope.name = "BookCntl"; - $scope.params = $routeParams; - } - - function ChapterCntl($scope, $routeParams) { - $scope.name = "ChapterCntl"; - $scope.params = $routeParams; - } - - - - it('should load and compile correct template', function() { - element('a:contains("Moby: Ch1")').click(); - var content = element('.doc-example-live [ng-view]').text(); - expect(content).toMatch(/controller\: ChapterCntl/); - expect(content).toMatch(/Book Id\: Moby/); - expect(content).toMatch(/Chapter Id\: 1/); - - element('a:contains("Scarlet")').click(); - content = element('.doc-example-live [ng-view]').text(); - expect(content).toMatch(/controller\: BookCntl/); - expect(content).toMatch(/Book Id\: Scarlet/); - }); - -
- */ - - -/** - * @ngdoc event - * @name ng.directive:ngView#$viewContentLoaded - * @eventOf ng.directive:ngView - * @eventType emit on the current ngView scope - * @description - * Emitted every time the ngView content is reloaded. - */ -var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile', - '$controller', - function($http, $templateCache, $route, $anchorScroll, $compile, - $controller) { - return { - restrict: 'ECA', - terminal: true, - link: function(scope, element, attr) { - var lastScope, - onloadExp = attr.onload || ''; - - scope.$on('$routeChangeSuccess', update); - update(); - - - function destroyLastScope() { - if (lastScope) { - lastScope.$destroy(); - lastScope = null; - } - } - - function clearContent() { - element.html(''); - destroyLastScope(); - } - - function update() { - var locals = $route.current && $route.current.locals, - template = locals && locals.$template; - - if (template) { - element.html(template); - destroyLastScope(); - - var link = $compile(element.contents()), - current = $route.current, - controller; - - lastScope = current.scope = scope.$new(); - if (current.controller) { - locals.$scope = lastScope; - controller = $controller(current.controller, locals); - element.children().data('$ngControllerController', controller); - } - - link(lastScope); - lastScope.$emit('$viewContentLoaded'); - lastScope.$eval(onloadExp); - - // $anchorScroll might listen on event... - $anchorScroll(); - } else { - clearContent(); - } - } - } - }; -}]; - /** * @ngdoc directive * @name ng.directive:script @@ -14271,8 +17290,8 @@ var scriptDirective = ['$templateCache', function($templateCache) { * Optionally `ngOptions` attribute can be used to dynamically generate a list of `` * DOM element. + * * `trackexpr`: Used when working with an array of objects. The result of this expression will be + * used to identify the objects in the array. The `trackexpr` will most likely refer to the + * `value` variable (e.g. `value.propertyName`). * * @example @@ -14381,8 +17403,8 @@ var scriptDirective = ['$templateCache', function($templateCache) { var ngOptionsDirective = valueFn({ terminal: true }); var selectDirective = ['$compile', '$parse', function($compile, $parse) { - //0000111110000000000022220000000000000000000000333300000000000000444444444444444440000000005555555555555555500000006666666666666666600000000000000077770 - var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/, + //0000111110000000000022220000000000000000000000333300000000000000444444444444444440000000005555555555555555500000006666666666666666600000000000000007777000000000000000000088888 + var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/, nullModelCtrl = {$setViewValue: noop}; return { @@ -14512,7 +17534,7 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { } }; - selectElement.bind('change', function() { + selectElement.on('change', function() { scope.$apply(function() { if (unknownOption.parent()) unknownOption.remove(); ngModelCtrl.$setViewValue(selectElement.val()); @@ -14538,7 +17560,7 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { } }); - selectElement.bind('change', function() { + selectElement.on('change', function() { scope.$apply(function() { var array = []; forEach(selectElement.find('option'), function(option) { @@ -14555,9 +17577,9 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { var match; if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) { - throw Error( - "Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" + - " but got '" + optionsExp + "'."); + throw minErr('ngOptions')('iexp', + "Expected expression in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_' but got '{0}'. Element: {1}", + optionsExp, startingTag(selectElement)); } var displayFn = $parse(match[2] || match[1]), @@ -14566,6 +17588,8 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { groupByFn = $parse(match[3] || ''), valueFn = $parse(match[2] ? match[1] : valueName), valuesFn = $parse(match[7]), + track = match[8], + trackFn = track ? $parse(match[8]) : null, // This is an array of array of existing option groups in DOM. We try to reuse these if possible // optionGroupsCache[0] is the options with no option group // optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element @@ -14587,7 +17611,7 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { // clear contents, we'll add what's needed based on the model selectElement.html(''); - selectElement.bind('change', function() { + selectElement.on('change', function() { scope.$apply(function() { var optionGroup, collection = valuesFn(scope) || [], @@ -14606,7 +17630,14 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { if ((optionElement = optionGroup[index].element)[0].selected) { key = optionElement.val(); if (keyName) locals[keyName] = key; - locals[valueName] = collection[key]; + if (trackFn) { + for (var trackIndex = 0; trackIndex < collection.length; trackIndex++) { + locals[valueName] = collection[trackIndex]; + if (trackFn(scope, locals) == key) break; + } + } else { + locals[valueName] = collection[key]; + } value.push(valueFn(scope, locals)); } } @@ -14618,9 +17649,19 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { } else if (key == ''){ value = null; } else { - locals[valueName] = collection[key]; - if (keyName) locals[keyName] = key; - value = valueFn(scope, locals); + if (trackFn) { + for (var trackIndex = 0; trackIndex < collection.length; trackIndex++) { + locals[valueName] = collection[trackIndex]; + if (trackFn(scope, locals) == key) { + value = valueFn(scope, locals); + break; + } + } + } else { + locals[valueName] = collection[key]; + if (keyName) locals[keyName] = key; + value = valueFn(scope, locals); + } } } ctrl.$setViewValue(value); @@ -14652,7 +17693,15 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { label; if (multiple) { - selectedSet = new HashMap(modelValue); + if (trackFn && isArray(modelValue)) { + selectedSet = new HashMap([]); + for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) { + locals[valueName] = modelValue[trackIndex]; + selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]); + } + } else { + selectedSet = new HashMap(modelValue); + } } // We now build up the list of options we need (we merge later) @@ -14664,15 +17713,21 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) { optionGroupNames.push(optionGroupName); } if (multiple) { - selected = selectedSet.remove(valueFn(scope, locals)) != undefined; + selected = selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals)) != undefined; } else { - selected = modelValue === valueFn(scope, locals); + if (trackFn) { + var modelCast = {}; + modelCast[valueName] = modelValue; + selected = trackFn(scope, modelCast) === trackFn(scope, locals); + } else { + selected = modelValue === valueFn(scope, locals); + } selectedSet = selectedSet || selected; // see if at least one item is selected } label = displayFn(scope, locals); // what will be seen by the user label = label === undefined ? '' : label; // doing displayFn(scope, locals) || '' overwrites zero values optionGroup.push({ - id: keyName ? keys[index] : index, // either the index into array or key from object + id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index), // either the index into array or key from object label: label, selected: selected // determine if we should be selected }); @@ -14820,7 +17875,7 @@ var optionDirective = ['$interpolate', function($interpolate) { selectCtrl.addOption(attr.value); } - element.bind('$destroy', function() { + element.on('$destroy', function() { selectCtrl.removeOption(attr.value); }); }; @@ -14844,4 +17899,4 @@ var styleDirective = valueFn({ }); })(window, document); -angular.element(document).find('head').append(''); \ No newline at end of file +angular.element(document).find('head').prepend(''); \ No newline at end of file diff --git a/dist/dependencies/lodash.js b/dist/dependencies/lodash.js index 7dc1deb6..088c15b9 100644 --- a/dist/dependencies/lodash.js +++ b/dist/dependencies/lodash.js @@ -1,7 +1,6 @@ /** * @license - * Lo-Dash 1.3.1 (Custom Build) - * Build: `lodash -o ./dist/lodash.compat.js` + * Lo-Dash 1.3.1 * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.4.4 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud Inc. @@ -343,6 +342,7 @@ 'push': null, 'shadowedProps': null, 'string': null, + 'support': null, 'top': '', 'trailing': false, 'true': false, @@ -833,96 +833,113 @@ * @param {Object} data The data object used to populate the text. * @returns {String} Returns the interpolated text. */ - var iteratorTemplate = function(obj) { - - var __p = 'var index, iterable = ' + - (obj.firstArg) + - ', result = ' + - (obj.init) + - ';\nif (!iterable) return result;\n' + - (obj.top) + - ';'; - if (obj.array) { - __p += '\nvar length = iterable.length; index = -1;\nif (' + - (obj.array) + - ') { '; - if (support.unindexedChars) { - __p += '\n if (isString(iterable)) {\n iterable = iterable.split(\'\')\n } '; - } - __p += '\n while (++index < length) {\n ' + - (obj.loop) + - ';\n }\n}\nelse { '; - } else if (support.nonEnumArgs) { - __p += '\n var length = iterable.length; index = -1;\n if (length && isArguments(iterable)) {\n while (++index < length) {\n index += \'\';\n ' + - (obj.loop) + - ';\n }\n } else { '; - } - - if (support.enumPrototypes) { - __p += '\n var skipProto = typeof iterable == \'function\';\n '; - } - - if (support.enumErrorProps) { - __p += '\n var skipErrorProps = iterable === errorProto || iterable instanceof Error;\n '; - } - - var conditions = []; if (support.enumPrototypes) { conditions.push('!(skipProto && index == "prototype")'); } if (support.enumErrorProps) { conditions.push('!(skipErrorProps && (index == "message" || index == "name"))'); } - - if (obj.useHas && obj.useKeys) { - __p += '\n var ownIndex = -1,\n ownProps = objectTypes[typeof iterable] && keys(iterable),\n length = ownProps ? ownProps.length : 0;\n\n while (++ownIndex < length) {\n index = ownProps[ownIndex];\n'; - if (conditions.length) { - __p += ' if (' + - (conditions.join(' && ')) + - ') {\n '; - } - __p += - (obj.loop) + - '; '; - if (conditions.length) { - __p += '\n }'; - } - __p += '\n } '; - } else { - __p += '\n for (index in iterable) {\n'; - if (obj.useHas) { conditions.push("hasOwnProperty.call(iterable, index)"); } if (conditions.length) { - __p += ' if (' + - (conditions.join(' && ')) + - ') {\n '; - } - __p += - (obj.loop) + - '; '; - if (conditions.length) { - __p += '\n }'; - } - __p += '\n } '; - if (support.nonEnumShadows) { - __p += '\n\n if (iterable !== objectProto) {\n var ctor = iterable.constructor,\n isProto = iterable === (ctor && ctor.prototype),\n className = iterable === stringProto ? stringClass : iterable === errorProto ? errorClass : toString.call(iterable),\n nonEnum = nonEnumProps[className];\n '; - for (k = 0; k < 7; k++) { - __p += '\n index = \'' + - (obj.shadowedProps[k]) + - '\';\n if ((!(isProto && nonEnum[index]) && hasOwnProperty.call(iterable, index))'; - if (!obj.useHas) { - __p += ' || (!nonEnum[index] && iterable[index] !== objectProto[index])'; - } - __p += ') {\n ' + - (obj.loop) + - ';\n } '; - } - __p += '\n } '; - } - - } - - if (obj.array || support.nonEnumArgs) { - __p += '\n}'; - } - __p += - (obj.bottom) + - ';\nreturn result'; - - return __p - }; + var iteratorTemplate = template( + // the `iterable` may be reassigned by the `top` snippet + 'var index, iterable = <%= firstArg %>, ' + + // assign the `result` variable an initial value + 'result = <%= init %>;\n' + + // exit early if the first argument is falsey + 'if (!iterable) return result;\n' + + // add code before the iteration branches + '<%= top %>;' + + + // array-like iteration: + '<% if (array) { %>\n' + + 'var length = iterable.length; index = -1;\n' + + 'if (<%= array %>) {' + + + // add support for accessing string characters by index if needed + ' <% if (support.unindexedChars) { %>\n' + + ' if (isString(iterable)) {\n' + + " iterable = iterable.split('')\n" + + ' }' + + ' <% } %>\n' + + + // iterate over the array-like value + ' while (++index < length) {\n' + + ' <%= loop %>;\n' + + ' }\n' + + '}\n' + + 'else {' + + + // object iteration: + // add support for iterating over `arguments` objects if needed + ' <% } else if (support.nonEnumArgs) { %>\n' + + ' var length = iterable.length; index = -1;\n' + + ' if (length && isArguments(iterable)) {\n' + + ' while (++index < length) {\n' + + " index += '';\n" + + ' <%= loop %>;\n' + + ' }\n' + + ' } else {' + + ' <% } %>' + + + // avoid iterating over `prototype` properties in older Firefox, Opera, and Safari + ' <% if (support.enumPrototypes) { %>\n' + + " var skipProto = typeof iterable == 'function';\n" + + ' <% } %>' + + + // avoid iterating over `Error.prototype` properties in older IE and Safari + ' <% if (support.enumErrorProps) { %>\n' + + ' var skipErrorProps = iterable === errorProto || iterable instanceof Error;\n' + + ' <% } %>' + + + // define conditions used in the loop + ' <%' + + ' var conditions = [];' + + ' if (support.enumPrototypes) { conditions.push(\'!(skipProto && index == "prototype")\'); }' + + ' if (support.enumErrorProps) { conditions.push(\'!(skipErrorProps && (index == "message" || index == "name"))\'); }' + + ' %>' + + + // iterate own properties using `Object.keys` + ' <% if (useHas && useKeys) { %>\n' + + ' var ownIndex = -1,\n' + + ' ownProps = objectTypes[typeof iterable] && keys(iterable),\n' + + ' length = ownProps ? ownProps.length : 0;\n\n' + + ' while (++ownIndex < length) {\n' + + ' index = ownProps[ownIndex];\n<%' + + " if (conditions.length) { %> if (<%= conditions.join(' && ') %>) {\n <% } %>" + + ' <%= loop %>;' + + ' <% if (conditions.length) { %>\n }<% } %>\n' + + ' }' + + + // else using a for-in loop + ' <% } else { %>\n' + + ' for (index in iterable) {\n<%' + + ' if (useHas) { conditions.push("hasOwnProperty.call(iterable, index)"); }' + + " if (conditions.length) { %> if (<%= conditions.join(' && ') %>) {\n <% } %>" + + ' <%= loop %>;' + + ' <% if (conditions.length) { %>\n }<% } %>\n' + + ' }' + + + // Because IE < 9 can't set the `[[Enumerable]]` attribute of an + // existing property and the `constructor` property of a prototype + // defaults to non-enumerable, Lo-Dash skips the `constructor` + // property when it infers it's iterating over a `prototype` object. + ' <% if (support.nonEnumShadows) { %>\n\n' + + ' if (iterable !== objectProto) {\n' + + " var ctor = iterable.constructor,\n" + + ' isProto = iterable === (ctor && ctor.prototype),\n' + + ' className = iterable === stringProto ? stringClass : iterable === errorProto ? errorClass : toString.call(iterable),\n' + + ' nonEnum = nonEnumProps[className];\n' + + ' <% for (k = 0; k < 7; k++) { %>\n' + + " index = '<%= shadowedProps[k] %>';\n" + + ' if ((!(isProto && nonEnum[index]) && hasOwnProperty.call(iterable, index))<%' + + ' if (!useHas) { %> || (!nonEnum[index] && iterable[index] !== objectProto[index])<% }' + + ' %>) {\n' + + ' <%= loop %>;\n' + + ' }' + + ' <% } %>\n' + + ' }' + + ' <% } %>' + + ' <% } %>' + + ' <% if (array || support.nonEnumArgs) { %>\n}<% } %>\n' + + + // add code to the bottom of the iteration function + '<%= bottom %>;\n' + + // finally, return the `result` + 'return result' + ); /** Reusable iterator options for `assign` and `defaults` */ var defaultsIteratorOptions = { @@ -1031,6 +1048,8 @@ // data properties data.shadowedProps = shadowedProps; + data.support = support; + // iterator options data.array = data.bottom = data.loop = data.top = ''; data.init = 'iterable'; @@ -5412,11 +5431,11 @@ text || (text = ''); // avoid missing dependencies when `iteratorTemplate` is not defined - options = defaults({}, options, settings); + options = iteratorTemplate ? defaults({}, options, settings) : settings; - var imports = defaults({}, options.imports, settings.imports), - importsKeys = keys(imports), - importsValues = values(imports); + var imports = iteratorTemplate && defaults({}, options.imports, settings.imports), + importsKeys = iteratorTemplate ? keys(imports) : ['_'], + importsValues = iteratorTemplate ? values(imports) : [lodash]; var isEvaluating, index = 0, @@ -5869,6 +5888,11 @@ }); } + // add pseudo private property to be used and removed during the build process + lodash._basicEach = basicEach; + lodash._iteratorTemplate = iteratorTemplate; + lodash._shimKeys = shimKeys; + return lodash; } diff --git a/dist/restangular.js b/dist/restangular.js index ccb72d33..b30979cd 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,6 +1,6 @@ /** * Restful Resources service for AngularJS apps - * @version v1.0.11 - 2013-08-12 + * @version v1.0.11 - 2013-08-14 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT @@ -60,7 +60,7 @@ module.provider('Restangular', function() { object.setDefaultRequestParams = function(values) { config.defaultRequestParams.common = values; } - + object.requestParams = config.defaultRequestParams; @@ -69,6 +69,8 @@ module.provider('Restangular', function() { config.defaultHeaders = headers; }; + object.defaultHeaders = config.defaultHeaders; + /** * Method overriders will set which methods are sent via POST with an X-HTTP-Method-Override **/ diff --git a/dist/restangular.min.js b/dist/restangular.min.js index e549c90f..0f02e481 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,8 +1,8 @@ /** * Restful Resources service for AngularJS apps - * @version v1.0.11 - 2013-08-12 + * @version v1.0.11 - 2013-08-14 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.fullResponseInterceptor=b.fullResponseInterceptor||function(a){return a},a.setFullResponseInterceptor=function(a){b.fullResponseInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),""===f||_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return c=f.fullResponseInterceptor(c,b,a),f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return f.useCannonicalId&&(e[f.restangularFields.cannonicalId]=f.getIdFromElem(e)),e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a)!==!1&&h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a)!==!1&&k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":"remove"===a?"DELETE":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},a.defaultHeaders=b.defaultHeaders,b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.fullResponseInterceptor=b.fullResponseInterceptor||function(a){return a},a.setFullResponseInterceptor=function(a){b.fullResponseInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),""===f||_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return c=f.fullResponseInterceptor(c,b,a),f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return f.useCannonicalId&&(e[f.restangularFields.cannonicalId]=f.getIdFromElem(e)),e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a)!==!1&&h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a)!==!1&&k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":"remove"===a?"DELETE":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index 457c19a0a174e0fef15acab1972d15696cdbcae1..d55d4de57ebcf6d0baf446b13992a96427893ef1 100644 GIT binary patch delta 183 zcmdn{fvNu^6K{YwGYc032s|s|o5-uc3#6PauQ&*P?P6f~I?*bZ(PZO_X&jUN>UbyX zNwQCl-!@%G)*`T|S(PZL^6`Q?!RNyY*XNo1 z&w+RHIZpP;L7d+vZ{QW)Je_M#16chV^;hc^bQl;ECMR?kG8#=>v0`&o&nlM9ZWG(o pn1KdPKEK@n)!@lIJ51z3R>8FbwTpw@0V5 Date: Wed, 14 Aug 2013 15:01:56 -0300 Subject: [PATCH 084/441] Added ETag support Fixes #230 --- dist/restangular.js | 3 ++- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 47247 -> 47311 bytes src/restangular.js | 3 ++- 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/dist/restangular.js b/dist/restangular.js index b30979cd..d26ecc8a 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -117,7 +117,8 @@ module.provider('Restangular', function() { route: "route", parentResource: "parentResource", restangularCollection: "restangularCollection", - cannonicalId: "__cannonicalId" + cannonicalId: "__cannonicalId", + etag: "restangularEtag" }; object.setRestangularFields = function(resFields) { config.restangularFields = diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 0f02e481..2e2462c3 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -5,4 +5,4 @@ * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},a.defaultHeaders=b.defaultHeaders,b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.fullResponseInterceptor=b.fullResponseInterceptor||function(a){return a},a.setFullResponseInterceptor=function(a){b.fullResponseInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),""===f||_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return c=f.fullResponseInterceptor(c,b,a),f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return f.useCannonicalId&&(e[f.restangularFields.cannonicalId]=f.getIdFromElem(e)),e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a)!==!1&&h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a)!==!1&&k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":"remove"===a?"DELETE":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},a.defaultHeaders=b.defaultHeaders,b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId",etag:"restangularEtag"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.fullResponseInterceptor=b.fullResponseInterceptor||function(a){return a},a.setFullResponseInterceptor=function(a){b.fullResponseInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),""===f||_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return c=f.fullResponseInterceptor(c,b,a),f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return f.useCannonicalId&&(e[f.restangularFields.cannonicalId]=f.getIdFromElem(e)),e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a)!==!1&&h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a)!==!1&&k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":"remove"===a?"DELETE":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index d55d4de57ebcf6d0baf446b13992a96427893ef1..be31b4b05245a58b0ae7ec3501ba28d1ae76c18b 100644 GIT binary patch delta 212 zcmeDG$aMZA6HkCQGYc032v}E4 Date: Wed, 14 Aug 2013 15:06:22 -0300 Subject: [PATCH 085/441] Forgot some stuff about ETag pushing now :D for #230 --- dist/restangular.js | 55 +++++++++++++++++++++++----------------- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 47311 -> 47760 bytes src/restangular.js | 55 +++++++++++++++++++++++----------------- 4 files changed, 65 insertions(+), 47 deletions(-) diff --git a/dist/restangular.js b/dist/restangular.js index d26ecc8a..74b80ce3 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -156,16 +156,23 @@ module.provider('Restangular', function() { * * The ResponseExtractor is a function that receives the response and the method executed. */ - config.responseExtractor = config.responseExtractor || function(response) { - return response; + + config.responseExtractor = config.responseExtractor || function(data, operation, + what, url, response, deferred) { + return data; }; - + object.setResponseExtractor = function(extractor) { config.responseExtractor = extractor; }; object.setResponseInterceptor = object.setResponseExtractor; + /** + * Response interceptor is called just before resolving promises. + */ + + /** * Request interceptor is called before sending an object to the server. */ @@ -192,17 +199,6 @@ module.provider('Restangular', function() { config.fullRequestInterceptor = interceptor; }; - /** - * Response interceptor is called just before resolving promises. - */ - config.fullResponseInterceptor = config.fullResponseInterceptor || function(data, response, deferred) { - return data; - }; - - object.setFullResponseInterceptor = function(interceptor) { - config.fullResponseInterceptor = interceptor; - }; - config.errorInterceptor = config.errorInterceptor || function() {}; object.setErrorInterceptor = function(interceptor) { @@ -379,11 +375,15 @@ module.provider('Restangular', function() { return resource; } - BaseCreator.prototype.resource = function(current, $http, callHeaders, callParams, what) { + BaseCreator.prototype.resource = function(current, $http, callHeaders, callParams, what, etag) { var params = _.defaults(callParams || {}, this.config.defaultRequestParams.common); var headers = _.defaults(callHeaders || {}, this.config.defaultHeaders); + if (etag) { + headers['If-None-Match'] = etag; + } + var url = this.base(current); url += what ? ("/" + what): ''; url += (this.config.suffix || ''); @@ -556,8 +556,6 @@ module.provider('Restangular', function() { function resolvePromise(deferred, response, data) { // Trigger the full response interceptor. - data = config.fullResponseInterceptor(data, response, deferred); - if (config.fullResponse) { return deferred.resolve(_.extend(response, { data: data @@ -649,6 +647,15 @@ module.provider('Restangular', function() { return restangularizePromise(deferred.promise, true) } + function parseResponse(resData, operation, route, fetchUrl, response, deferred) { + var data = config.responseExtractor(resData, operation, route, fetchUrl, response, deferred); + var etag = response.headers("ETag"); + if (data && etag) { + data[config.restangularFields.etag] = etag; + } + return data; + } + function fetchFunction(what, reqParams, headers) { var __this = this; @@ -661,9 +668,10 @@ module.provider('Restangular', function() { var request = config.fullRequestInterceptor(null, operation, whatFetched, url, headers || {}, reqParams || {}); - urlHandler.resource(this, $http, request.headers, request.params, what).getList().then(function(response) { + urlHandler.resource(this, $http, request.headers, request.params, what, + this[config.restangularFields.etag]).getList().then(function(response) { var resData = response.data; - var data = config.responseExtractor(resData, operation, whatFetched, url); + var data = parseResponse(resData, operation, whatFetched, url, response, deferred); var processedData = _.map(data, function(elem) { if (!__this[config.restangularFields.restangularCollection]) { return restangularizeElem(__this, elem, what); @@ -691,6 +699,7 @@ module.provider('Restangular', function() { function elemFunction(operation, what, params, obj, headers) { var __this = this; + var etag = this[config.restangularFields.etag]; var deferred = $q.defer(); var resParams = params || {}; var route = what || this[config.restangularFields.route]; @@ -702,7 +711,7 @@ module.provider('Restangular', function() { var okCallback = function(response) { var resData = response.data; - var elem = config.responseExtractor(resData, operation, route, fetchUrl); + var elem = parseResponse(resData, operation, route, fetchUrl, response, deferred); if (elem) { if (operation === "post" && !__this[config.restangularFields.restangularCollection]) { @@ -733,14 +742,14 @@ module.provider('Restangular', function() { if (config.isSafe(operation)) { if (isOverrideOperation) { urlHandler.resource(this, $http, callHeaders, request.params, - what)[callOperation]({}).then(okCallback, errorCallback); + what, etag)[callOperation]({}).then(okCallback, errorCallback); } else { urlHandler.resource(this, $http, callHeaders, request.params, - what)[callOperation]().then(okCallback, errorCallback); + what, etag)[callOperation]().then(okCallback, errorCallback); } } else { urlHandler.resource(this, $http, callHeaders, request.params, - what)[callOperation](request.element).then(okCallback, errorCallback); + what, etag)[callOperation](request.element).then(okCallback, errorCallback); } return restangularizePromise(deferred.promise); diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 2e2462c3..aa24e364 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -5,4 +5,4 @@ * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},a.defaultHeaders=b.defaultHeaders,b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId",etag:"restangularEtag"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.fullResponseInterceptor=b.fullResponseInterceptor||function(a){return a},a.setFullResponseInterceptor=function(a){b.fullResponseInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f){var g=_.defaults(e||{},this.config.defaultRequestParams.common),h=_.defaults(d||{},this.config.defaultHeaders),i=this.base(a);return i+=f?"/"+f:"",i+=this.config.suffix||"",c(this.config,b,i,{getList:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),get:this.config.withHttpDefaults({method:"GET",params:g,headers:h}),put:this.config.withHttpDefaults({method:"PUT",params:g,headers:h}),post:this.config.withHttpDefaults({method:"POST",params:g,headers:h}),remove:this.config.withHttpDefaults({method:"DELETE",params:g,headers:h}),head:this.config.withHttpDefaults({method:"HEAD",params:g,headers:h}),trace:this.config.withHttpDefaults({method:"TRACE",params:g,headers:h}),options:this.config.withHttpDefaults({method:"OPTIONS",params:g,headers:h}),patch:this.config.withHttpDefaults({method:"PATCH",params:g,headers:h})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),""===f||_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(H.fetchUrl,H,b),b.addRestangularMethod=_.bind(E,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return c=f.fullResponseInterceptor(c,b,a),f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(D,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(D,a,d)})}),a.customGETLIST=_.bind(t,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return f.useCannonicalId&&(e[f.restangularFields.cannonicalId]=f.getIdFromElem(e)),e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(v,e),e.getList=_.bind(t,e),e.put=_.bind(x,e),e.post=_.bind(y,e),e.remove=_.bind(w,e),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),o(e),f.transformElem(e,!1,c,G)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(y,e,null),e.head=_.bind(z,e),e.trace=_.bind(A,e),e.putElement=_.bind(s,e),e.options=_.bind(B,e),e.patch=_.bind(C,e),e.getList=_.bind(t,e,null),o(e),f.transformElem(e,!0,c,G)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,e){var g=this,h=d.defer(),i="getList",k=H.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return H.resource(this,c,n.headers,n.params,a).getList().then(function(b){var c=b.data,d=f.responseExtractor(c,i,l,k),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a)!==!1&&h.reject(a)}),j(h.promise,!0)}function u(a,b,e,g,h){var i=this,k=d.defer(),l=e||{},o=b||this[f.restangularFields.route],p=H.fetchUrl(this,b),r=g||("remove"===a?void 0:n(this)),s=f.fullRequestInterceptor(r,a,o,p,h||{},l||{}),t=function(c){var d=c.data,e=f.responseExtractor(d,a,o,p);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(k,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(k,c,q(i,e,b)):m(k,c,void 0)},u=function(a){f.errorInterceptor(a)!==!1&&k.reject(a)},v=a,w=_.extend({},s.headers),x=f.isOverridenMethod(a);return x&&(v="post",w=_.extend(w,{"X-HTTP-Method-Override":"remove"===a?"DELETE":a})),f.isSafe(a)?x?H.resource(this,c,w,s.params,b)[v]({}).then(t,u):H.resource(this,c,w,s.params,b)[v]().then(t,u):H.resource(this,c,w,s.params,b)[v](s.element).then(t,u),j(k.promise)}function v(a,b){return _.bind(u,this)("get",void 0,a,void 0,b)}function w(a,b){return _.bind(u,this)("remove",void 0,a,void 0,b)}function x(a,b){return _.bind(u,this)("put",void 0,a,void 0,b)}function y(a,b,c,d){return _.bind(u,this)("post",a,c,b,d)}function z(a,b){return _.bind(u,this)("head",void 0,a,void 0,b)}function A(a,b){return _.bind(u,this)("trace",void 0,a,void 0,b)}function B(a,b){return _.bind(u,this)("options",void 0,a,void 0,b)}function C(a,b,c){return _.bind(u,this)("patch",void 0,b,a,c)}function D(a,b,c,d,e){return _.bind(u,this)(a,b,c,e,d)}function E(a,b,c,d,e,g){var h;h="getList"===b?_.bind(t,this,c):_.bind(D,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function F(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var G={},H=new f.urlCreatorFactory[f.urlCreator];return H.setConfig(f),a.init(G,f),G.copy=_.bind(p,G),G.withConfig=_.bind(F,G),G.one=_.bind(h,G,null),G.all=_.bind(i,G,null),G.restangularizeElement=_.bind(q,G),G.restangularizeCollection=_.bind(r,G),G}return e(b)}]})}(); \ No newline at end of file +!function(){var a=angular.module("restangular",[]);a.provider("Restangular",function(){var a={};a.init=function(a,b){function c(a,b,c,d){var e={};return _.each(_.keys(d),function(f){var g=d[f];g.params=_.extend({},g.params,a.defaultRequestParams[g.method.toLowerCase()]),_.isEmpty(g.params)&&delete g.params,e[f]=a.isSafe(g.method)?function(){return b(_.extend(g,{url:c}))}:function(a){return b(_.extend(g,{url:c,data:a}))}}),e}var d=["get","head","options","trace"];b.isSafe=function(a){return _.contains(d,a.toLowerCase())},b.baseUrl=_.isUndefined(b.baseUrl)?"":b.baseUrl,a.setBaseUrl=function(a){b.baseUrl="/"===_.last(a)?_.initial(a).join(""):a},b.extraFields=b.extraFields||[],a.setExtraFields=function(a){b.extraFields=a},b.defaultHttpFields=b.defaultHttpFields||{},a.setDefaultHttpFields=function(a){b.defaultHttpFields=a},b.withHttpDefaults=function(a){return _.defaults(a,b.defaultHttpFields)},b.defaultRequestParams=b.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},a.setDefaultRequestParams=function(a){b.defaultRequestParams.common=a},a.requestParams=b.defaultRequestParams,b.defaultHeaders=b.defaultHeaders||{},a.setDefaultHeaders=function(a){b.defaultHeaders=a},a.defaultHeaders=b.defaultHeaders,b.methodOverriders=b.methodOverriders||[],a.setMethodOverriders=function(a){var c=_.extend([],a);b.isOverridenMethod("delete",c)&&c.push("remove"),b.methodOverriders=c},b.isOverridenMethod=function(a,c){var d=c||b.methodOverriders;return!_.isUndefined(_.find(d,function(b){return b.toLowerCase()===a.toLowerCase()}))},b.urlCreator=b.urlCreator||"path",a.setUrlCreator=function(a){if(!_.has(b.urlCreatorFactory,a))throw new Error("URL Path selected isn't valid");b.urlCreator=a},b.restangularFields=b.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId",etag:"restangularEtag"},a.setRestangularFields=function(a){b.restangularFields=_.extend(b.restangularFields,a)},b.setIdToElem=function(a,c){var d=b.restangularFields.id.split("."),e=a;_.each(_.initial(d),function(a){e[a]={},e=e[a]}),e[_.last(d)]=c},b.getIdFromElem=function(a){var c=b.restangularFields.id.split("."),d=angular.copy(a);return _.each(c,function(a){d=d[a]}),d},b.useCannonicalId=_.isUndefined(b.useCannonicalId)?!1:b.useCannonicalId,a.setUseCannonicalId=function(a){b.useCannonicalId=a},b.responseExtractor=b.responseExtractor||function(a){return a},a.setResponseExtractor=function(a){b.responseExtractor=a},a.setResponseInterceptor=a.setResponseExtractor,b.fullRequestInterceptor=b.fullRequestInterceptor||function(a,b,c,d,e,f){return{element:a,headers:e,params:f}},a.setRequestInterceptor=function(a){b.fullRequestInterceptor=function(b,c,d,e,f,g){return{headers:f,params:g,element:a(b,c,d,e)}}},a.setFullRequestInterceptor=function(a){b.fullRequestInterceptor=a},b.errorInterceptor=b.errorInterceptor||function(){},a.setErrorInterceptor=function(a){b.errorInterceptor=a},b.onBeforeElemRestangularized=b.onBeforeElemRestangularized||function(a){return a},a.setOnBeforeElemRestangularized=function(a){b.onBeforeElemRestangularized=a},b.onElemRestangularized=b.onElemRestangularized||function(a){return a},a.setOnElemRestangularized=function(a){b.onElemRestangularized=a},a.setListTypeIsArray=function(){},b.shouldSaveParent=b.shouldSaveParent||function(){return!0},a.setParentless=function(a){_.isArray(a)?b.shouldSaveParent=function(b){return!_.contains(a,b)}:_.isBoolean(a)&&(b.shouldSaveParent=function(){return!a})},b.suffix=_.isUndefined(b.suffix)?null:b.suffix,a.setRequestSuffix=function(a){b.suffix=a},b.transformers=b.transformers||{},a.addElementTransformer=function(a,c,d){var e=null,f=null;2===arguments.length?f=c:(f=d,e=c);var g=b.transformers[a];g||(g=b.transformers[a]=[]),g.push(function(a,b){return _.isNull(e)||a==e?f(b):b})},a.extendCollection=function(b,c){return a.addElementTransformer(b,!0,c)},a.extendModel=function(b,c){return a.addElementTransformer(b,!1,c)},b.transformElem=function(a,c,d,e){var f=b.transformers[d],g=a;return f&&_.each(f,function(a){g=a(c,g)}),b.onElemRestangularized(g,c,d,e)},b.fullResponse=_.isUndefined(b.fullResponse)?!1:b.fullResponse,a.setFullResponse=function(a){b.fullResponse=a},b.urlCreatorFactory={};var e=function(){};e.prototype.setConfig=function(a){this.config=a},e.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},e.prototype.resource=function(a,b,d,e,f,g){var h=_.defaults(e||{},this.config.defaultRequestParams.common),i=_.defaults(d||{},this.config.defaultHeaders);g&&(i["If-None-Match"]=g);var j=this.base(a);return j+=f?"/"+f:"",j+=this.config.suffix||"",c(this.config,b,j,{getList:this.config.withHttpDefaults({method:"GET",params:h,headers:i}),get:this.config.withHttpDefaults({method:"GET",params:h,headers:i}),put:this.config.withHttpDefaults({method:"PUT",params:h,headers:i}),post:this.config.withHttpDefaults({method:"POST",params:h,headers:i}),remove:this.config.withHttpDefaults({method:"DELETE",params:h,headers:i}),head:this.config.withHttpDefaults({method:"HEAD",params:h,headers:i}),trace:this.config.withHttpDefaults({method:"TRACE",params:h,headers:i}),options:this.config.withHttpDefaults({method:"OPTIONS",params:h,headers:i}),patch:this.config.withHttpDefaults({method:"PATCH",params:h,headers:i})})};var f=function(){};f.prototype=new e,f.prototype.base=function(a){var c=this;return this.config.baseUrl+_.reduce(this.parentsArray(a),function(a,d){var e=a+"/"+d[c.config.restangularFields.route];if(!d[c.config.restangularFields.restangularCollection]){var f;f=b.useCannonicalId?d[b.restangularFields.cannonicalId]:c.config.getIdFromElem(d),""===f||_.isUndefined(f)||_.isNull(f)||(e+="/"+f)}return e},"")},f.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},b.urlCreatorFactory.path=f};var b={};a.init(this,b),this.$get=["$http","$q",function(c,d){function e(f){function g(a,b,c){if(b[f.restangularFields.route]=c,b.getRestangularUrl=_.bind(I.fetchUrl,I,b),b.addRestangularMethod=_.bind(F,b),b.one=_.bind(h,b,b),b.all=_.bind(i,b,b),a&&f.shouldSaveParent(c)){var d=_.union(_.values(_.pick(f.restangularFields,["id","route","parentResource"])),f.extraFields);b[f.restangularFields.parentResource]=_.pick(a,d)}else b[f.restangularFields.parentResource]=null;return b}function h(a,b,c){var d={};return f.setIdToElem(d,c),q(a,d,b)}function i(a,b){return r(a,{},b,!0)}function j(a,b){return a.call=_.bind(k,a),a.get=_.bind(l,a),a[f.restangularFields.restangularCollection]=b,b&&(a.push=_.bind(k,a,"push")),a}function k(a){var b=d.defer(),c=arguments;return this.then(function(d){var e=Array.prototype.slice.call(c,1),f=d[a];f.apply(d,e),b.resolve(d)}),j(b.promise,this[f.restangularFields.restangularCollection])}function l(a){var b=d.defer();return this.then(function(c){b.resolve(c[a])}),j(b.promise,this[f.restangularFields.restangularCollection])}function m(a,b,c){return f.fullResponse?a.resolve(_.extend(b,{data:c})):(a.resolve(c),void 0)}function n(a){return _.omit(a,_.values(_.omit(f.restangularFields,"id")))}function o(a){a.customOperation=_.bind(E,a),_.each(["put","post","get","delete"],function(b){_.each(["do","custom"],function(c){var d="delete"===b?"remove":b,e=c+b.toUpperCase();a[e]=_.bind(E,a,d)})}),a.customGETLIST=_.bind(u,a),a.doGETLIST=a.customGETLIST}function p(a){var b=angular.copy(a);return q(b[f.restangularFields.parentResource],b,b[f.restangularFields.route])}function q(a,b,c){var d=f.onBeforeElemRestangularized(b,!1,c),e=g(a,d,c);return f.useCannonicalId&&(e[f.restangularFields.cannonicalId]=f.getIdFromElem(e)),e[f.restangularFields.restangularCollection]=!1,e.get=_.bind(w,e),e.getList=_.bind(u,e),e.put=_.bind(y,e),e.post=_.bind(z,e),e.remove=_.bind(x,e),e.head=_.bind(A,e),e.trace=_.bind(B,e),e.options=_.bind(C,e),e.patch=_.bind(D,e),o(e),f.transformElem(e,!1,c,H)}function r(a,b,c){var d=f.onBeforeElemRestangularized(b,!0,c),e=g(a,d,c);return e[f.restangularFields.restangularCollection]=!0,e.post=_.bind(z,e,null),e.head=_.bind(A,e),e.trace=_.bind(B,e),e.putElement=_.bind(s,e),e.options=_.bind(C,e),e.patch=_.bind(D,e),e.getList=_.bind(u,e,null),o(e),f.transformElem(e,!0,c,H)}function s(a,b,c){var e=this,f=this[a],g=d.defer();return f.put(b,c).then(function(b){var c=p(e);c[a]=b,g.resolve(c)},function(a){g.reject(a)}),j(g.promise,!0)}function t(a,b,c,d,e,g){var h=f.responseExtractor(a,b,c,d,e,g),i=e.headers("ETag");return h&&i&&(h[f.restangularFields.etag]=i),h}function u(a,b,e){var g=this,h=d.defer(),i="getList",k=I.fetchUrl(this,a),l=a||g[f.restangularFields.route],n=f.fullRequestInterceptor(null,i,l,k,e||{},b||{});return I.resource(this,c,n.headers,n.params,a,this[f.restangularFields.etag]).getList().then(function(b){var c=b.data,d=t(c,i,l,k,b,h),e=_.map(d,function(b){return g[f.restangularFields.restangularCollection]?q(g[f.restangularFields.parentResource],b,g[f.restangularFields.route]):q(g,b,a)});e=_.extend(d,e),g[f.restangularFields.restangularCollection]?m(h,b,r(null,e,g[f.restangularFields.route])):m(h,b,r(g,e,a))},function(a){f.errorInterceptor(a)!==!1&&h.reject(a)}),j(h.promise,!0)}function v(a,b,e,g,h){var i=this,k=this[f.restangularFields.etag],l=d.defer(),o=e||{},p=b||this[f.restangularFields.route],r=I.fetchUrl(this,b),s=g||("remove"===a?void 0:n(this)),u=f.fullRequestInterceptor(s,a,p,r,h||{},o||{}),v=function(c){var d=c.data,e=t(d,a,p,r,c,l);e?"post"!==a||i[f.restangularFields.restangularCollection]?m(l,c,q(i[f.restangularFields.parentResource],e,i[f.restangularFields.route])):m(l,c,q(i,e,b)):m(l,c,void 0)},w=function(a){f.errorInterceptor(a)!==!1&&l.reject(a)},x=a,y=_.extend({},u.headers),z=f.isOverridenMethod(a);return z&&(x="post",y=_.extend(y,{"X-HTTP-Method-Override":"remove"===a?"DELETE":a})),f.isSafe(a)?z?I.resource(this,c,y,u.params,b,k)[x]({}).then(v,w):I.resource(this,c,y,u.params,b,k)[x]().then(v,w):I.resource(this,c,y,u.params,b,k)[x](u.element).then(v,w),j(l.promise)}function w(a,b){return _.bind(v,this)("get",void 0,a,void 0,b)}function x(a,b){return _.bind(v,this)("remove",void 0,a,void 0,b)}function y(a,b){return _.bind(v,this)("put",void 0,a,void 0,b)}function z(a,b,c,d){return _.bind(v,this)("post",a,c,b,d)}function A(a,b){return _.bind(v,this)("head",void 0,a,void 0,b)}function B(a,b){return _.bind(v,this)("trace",void 0,a,void 0,b)}function C(a,b){return _.bind(v,this)("options",void 0,a,void 0,b)}function D(a,b,c){return _.bind(v,this)("patch",void 0,b,a,c)}function E(a,b,c,d,e){return _.bind(v,this)(a,b,c,e,d)}function F(a,b,c,d,e,g){var h;h="getList"===b?_.bind(u,this,c):_.bind(E,this,b,c);var i=function(a,b,c){var f=_.defaults({params:a,headers:b,elem:c},{params:d,headers:e,elem:g});return h(f.params,f.headers,f.elem)};this[a]=f.isSafe(b)?i:function(a,b,c){return i(b,c,a)}}function G(c){var d=angular.copy(b);return a.init(d,d),c(d),e(d)}var H={},I=new f.urlCreatorFactory[f.urlCreator];return I.setConfig(f),a.init(H,f),H.copy=_.bind(p,H),H.withConfig=_.bind(G,H),H.one=_.bind(h,H,null),H.all=_.bind(i,H,null),H.restangularizeElement=_.bind(q,H),H.restangularizeCollection=_.bind(r,H),H}return e(b)}]})}(); \ No newline at end of file diff --git a/dist/restangular.zip b/dist/restangular.zip index be31b4b05245a58b0ae7ec3501ba28d1ae76c18b..bf0fb2e662867b9db3cf57feb1b3f48438c1b1e1 100644 GIT binary patch delta 2242 zcma)8ZA=qq9H&rfr@gC3TdsFdii9nh zW^nLW>4PpY`gCcQrY-}8Te ze*b%V`;Yw0qx|CTT?O`{Jo;JswAj67DYd4v@l@5BTjP0ox5npuKh#0Px>9(OzY6X+ ztD)Z6Y!3;l0F2bMdPo#h#Au2Pe>Ftl#Mufs@B9tA8{RWas970TrN8gGUSQatV5)RG z^OMto7_15rxV!mJ*z&gBZV31Nbx_{1%5|uvE8Mm>9>Z;W1T`qO9AT3n8o|S+~DOh`3=xPYv~6Ld#`59y90rewSJQ2T4~6bztQO z72VbFu)7}E#!47F-URzb>-0>dBOe~7>*3tVRj~Gev(T`B+fsT(s?G3WZwsv7=%D54 zpGU73I?Vi_;y|O>qPv|nM(uITkza>?I&m<6g&(tIS|asDyTd0pIjojz!{1xW&FNpW zOTBEQzr2zj{L#M)QUfS2kABzY!Q`S-|MC;IL_hl35yxs2;YJ1pg%RQAIiF2}{E0Tk z7x8#l>5%)GGjkv2Bb<+_Mq$H5OcT`kf0( z0pPE$+WfHY;#u<4FE-gU{g;cfZEOf(4qiO3OAr23V{7mri}zf zF-?|f;{O{6Zd~%V{)gWeRSvG{W?KNZOwSz%q7aE>F^vyq%Qbzrm|LLgGfR$I!3~ZBzw}Mejxz^XKMB8%e!p0K{z_=q;~a23?%a*ZwQC6 z!g46iq=ENl-&#>8M@~>Y%*l#_BP6-6$7k9de+Br?fop32jfzRS4Ud(xhYDq10jGnDeS4jwvK9tDTBC?EK9P}HwYE;oGWdSYvp#&JOlId)W@m$SK*Pd zTAFXI?R>Gf;)S-l?WVVtzPcAYoBUQNGJenJf+#t-tO71k}8_&*2YeAgWSg!BBDU{O%U)3vTVUp4ov8w3bBX=Ute2WXgG#7u{yYSt;kL# ncyNueEkWtx>(Bk$fIW+EFe~pNmr7;hg88oXYgwnw|W<9gSX zy@bRM#srCze^>lyv*b}#I!cf;*ftKnz=1M6t(VlB+9X@a{gM@!m68=bJ!?Sw$P7Z$o* z@O!JTE-o4(jQNw$zTE}q+Ip#i^;2703+z194C=A9FvQitw%y;-e=8F@+v21q0Rd*Z zo82!f2G%948LG~fJT0ZSmW9iYmDE^Ym zKhmE)WBqpGtr}S4_d##+IU?C;eQ)e?f@kb2_;Ku>wJ<*HE_LEX?(qIsk;6fs^|TXy zYv>H?>PVQG%t4&hR3(e6QW9c(wFD+Ftb=dPd0c~4>Tv(O7w(*IaN5>Z@`C29=f-lP z9!SFdi(w`O8wy<=NEVEgoaJL;7PBH3*0EvgN1LM%4_N^op9n50~A`lKu0tP)%FAKDt!nit-6;NU0-w z21VhQkAuvB_3S5l?Pf_xENgL9^H~YSkjNnz{j|vR!;UNOlk@8X_8s|`_< z7UFyyC$P?PC?nwU@v#Y{3bFBV*mT_wTAy=0(uBtYWht&vj6*uSdp%g26%z1e>-v4H zjzpv)4W&vBGW6t-AtX#iqTpdAJ7`>xc)Ixr6Da&Q$7MWr&WmX*%$b5Zu8khdTau*X!)KTYl}&god7^uJ+$$ejQH diff --git a/src/restangular.js b/src/restangular.js index 34ef952a..f6af1483 100644 --- a/src/restangular.js +++ b/src/restangular.js @@ -149,16 +149,23 @@ module.provider('Restangular', function() { * * The ResponseExtractor is a function that receives the response and the method executed. */ - config.responseExtractor = config.responseExtractor || function(response) { - return response; + + config.responseExtractor = config.responseExtractor || function(data, operation, + what, url, response, deferred) { + return data; }; - + object.setResponseExtractor = function(extractor) { config.responseExtractor = extractor; }; object.setResponseInterceptor = object.setResponseExtractor; + /** + * Response interceptor is called just before resolving promises. + */ + + /** * Request interceptor is called before sending an object to the server. */ @@ -185,17 +192,6 @@ module.provider('Restangular', function() { config.fullRequestInterceptor = interceptor; }; - /** - * Response interceptor is called just before resolving promises. - */ - config.fullResponseInterceptor = config.fullResponseInterceptor || function(data, response, deferred) { - return data; - }; - - object.setFullResponseInterceptor = function(interceptor) { - config.fullResponseInterceptor = interceptor; - }; - config.errorInterceptor = config.errorInterceptor || function() {}; object.setErrorInterceptor = function(interceptor) { @@ -372,11 +368,15 @@ module.provider('Restangular', function() { return resource; } - BaseCreator.prototype.resource = function(current, $http, callHeaders, callParams, what) { + BaseCreator.prototype.resource = function(current, $http, callHeaders, callParams, what, etag) { var params = _.defaults(callParams || {}, this.config.defaultRequestParams.common); var headers = _.defaults(callHeaders || {}, this.config.defaultHeaders); + if (etag) { + headers['If-None-Match'] = etag; + } + var url = this.base(current); url += what ? ("/" + what): ''; url += (this.config.suffix || ''); @@ -549,8 +549,6 @@ module.provider('Restangular', function() { function resolvePromise(deferred, response, data) { // Trigger the full response interceptor. - data = config.fullResponseInterceptor(data, response, deferred); - if (config.fullResponse) { return deferred.resolve(_.extend(response, { data: data @@ -642,6 +640,15 @@ module.provider('Restangular', function() { return restangularizePromise(deferred.promise, true) } + function parseResponse(resData, operation, route, fetchUrl, response, deferred) { + var data = config.responseExtractor(resData, operation, route, fetchUrl, response, deferred); + var etag = response.headers("ETag"); + if (data && etag) { + data[config.restangularFields.etag] = etag; + } + return data; + } + function fetchFunction(what, reqParams, headers) { var __this = this; @@ -654,9 +661,10 @@ module.provider('Restangular', function() { var request = config.fullRequestInterceptor(null, operation, whatFetched, url, headers || {}, reqParams || {}); - urlHandler.resource(this, $http, request.headers, request.params, what).getList().then(function(response) { + urlHandler.resource(this, $http, request.headers, request.params, what, + this[config.restangularFields.etag]).getList().then(function(response) { var resData = response.data; - var data = config.responseExtractor(resData, operation, whatFetched, url); + var data = parseResponse(resData, operation, whatFetched, url, response, deferred); var processedData = _.map(data, function(elem) { if (!__this[config.restangularFields.restangularCollection]) { return restangularizeElem(__this, elem, what); @@ -684,6 +692,7 @@ module.provider('Restangular', function() { function elemFunction(operation, what, params, obj, headers) { var __this = this; + var etag = this[config.restangularFields.etag]; var deferred = $q.defer(); var resParams = params || {}; var route = what || this[config.restangularFields.route]; @@ -695,7 +704,7 @@ module.provider('Restangular', function() { var okCallback = function(response) { var resData = response.data; - var elem = config.responseExtractor(resData, operation, route, fetchUrl); + var elem = parseResponse(resData, operation, route, fetchUrl, response, deferred); if (elem) { if (operation === "post" && !__this[config.restangularFields.restangularCollection]) { @@ -726,14 +735,14 @@ module.provider('Restangular', function() { if (config.isSafe(operation)) { if (isOverrideOperation) { urlHandler.resource(this, $http, callHeaders, request.params, - what)[callOperation]({}).then(okCallback, errorCallback); + what, etag)[callOperation]({}).then(okCallback, errorCallback); } else { urlHandler.resource(this, $http, callHeaders, request.params, - what)[callOperation]().then(okCallback, errorCallback); + what, etag)[callOperation]().then(okCallback, errorCallback); } } else { urlHandler.resource(this, $http, callHeaders, request.params, - what)[callOperation](request.element).then(okCallback, errorCallback); + what, etag)[callOperation](request.element).then(okCallback, errorCallback); } return restangularizePromise(deferred.promise); From f0aea53c0ff4ef07c1274981e8a5417e83b2412d Mon Sep 17 00:00:00 2001 From: Martin Gontovnikas Date: Wed, 14 Aug 2013 16:23:33 -0300 Subject: [PATCH 086/441] Added URL feature :) Fixes #227 --- Gruntfile.js | 9 +- dist/dependencies/angular-resource.js | 457 - dist/dependencies/angular.js | 17902 ------------------------ dist/dependencies/lodash.js | 5933 -------- dist/restangular.js | 118 +- dist/restangular.min.js | 2 +- dist/restangular.zip | Bin 47760 -> 51293 bytes src/restangular.js | 118 +- 8 files changed, 188 insertions(+), 24351 deletions(-) delete mode 100644 dist/dependencies/angular-resource.js delete mode 100644 dist/dependencies/angular.js delete mode 100644 dist/dependencies/lodash.js diff --git a/Gruntfile.js b/Gruntfile.js index e6a5bc56..36ae3bee 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -29,11 +29,6 @@ module.exports = function(grunt) { zip: { '<%= dirs.dest %>/restangular.zip': ['<%= dirs.dest %>/<%= pkg.name %>.js', '<%= dirs.dest %>/<%= pkg.name %>.min.js'] }, - bower: { - dev: { - dest: '<%= dirs.dest %>/dependencies' - } - }, bowerInstall: { install: { } @@ -118,8 +113,6 @@ module.exports = function(grunt) { grunt.renameTask("bower", "bowerInstall"); - grunt.loadNpmTasks('grunt-bower'); - grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-conventional-changelog'); @@ -131,7 +124,7 @@ module.exports = function(grunt) { grunt.registerTask('default', ['build']); // Build task. - grunt.registerTask('build', ['bowerInstall', 'bower', 'karma:build', 'karma:buildUnderscore', 'concat', 'uglify', 'zip']); + grunt.registerTask('build', ['bowerInstall', 'karma:build', 'karma:buildUnderscore', 'concat', 'uglify', 'zip']); grunt.registerTask('test', ['karma:build', 'karma:buildUnderscore']); diff --git a/dist/dependencies/angular-resource.js b/dist/dependencies/angular-resource.js deleted file mode 100644 index d67f501c..00000000 --- a/dist/dependencies/angular-resource.js +++ /dev/null @@ -1,457 +0,0 @@ -/** - * @license AngularJS v1.0.7 - * (c) 2010-2012 Google, Inc. http://angularjs.org - * License: MIT - */ -(function(window, angular, undefined) { -'use strict'; - -/** - * @ngdoc overview - * @name ngResource - * @description - */ - -/** - * @ngdoc object - * @name ngResource.$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 ng.$http $http} service. - * - * # Installation - * To use $resource make sure you have included the `angular-resource.js` that comes in Angular - * package. You can also find this file on Google CDN, bower as well as at - * {@link http://code.angularjs.org/ code.angularjs.org}. - * - * Finally load the module in your application: - * - * angular.module('app', ['ngResource']); - * - * and you are ready to get started! - * - * @param {string} url A parameterized URL template with parameters prefixed by `:` as in - * `/user/:username`. If you are using a URL with a port number (e.g. - * `http://example.com:8080/api`), you'll need to escape the colon character before the port - * number, like this: `$resource('http://example.com\\:8080/api')`. - * - * @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.=} 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 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. The actions `save`, `remove` and `delete` 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: - *
-        var User = $resource('/user/:userId', {userId:'@id'});
-        var user = User.get({userId:123}, function() {
-          user.abc = true;
-          user.$save();
-        });
-     
- * - * 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 - * - *
-     // 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(function() {
-       // 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'}
-     });
-
-     // 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);
- * 
- * - * 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. - -
-     var User = $resource('/user/:userId', {userId:'@id'});
-     var user = User.get({userId:123}, function() {
-       user.abc = true;
-       user.$save();
-     });
-   
- * - * 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: - * -
-     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
-       });
-     });
-   
- - * # Buzz client - - Let's look at what a buzz client created with the `$resource` service looks like: - - - - -
- - -
-
-

- - {{item.actor.name}} - Expand replies: {{item.links.replies[0].count}} -

- {{item.object.content | html}} -
- - {{reply.actor.name}}: {{reply.content | html}} -
-
-
-
- - -
- */ -angular.module('ngResource', ['ng']). - factory('$resource', ['$http', '$parse', function($http, $parse) { - var DEFAULT_ACTIONS = { - 'get': {method:'GET'}, - 'save': {method:'POST'}, - 'query': {method:'GET', isArray:true}, - 'remove': {method:'DELETE'}, - 'delete': {method:'DELETE'} - }; - var noop = angular.noop, - forEach = angular.forEach, - extend = angular.extend, - copy = angular.copy, - isFunction = angular.isFunction, - getter = function(obj, path) { - return $parse(path)(obj); - }; - - /** - * We need our custom method because encodeURIComponent is too aggressive and doesn't follow - * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path - * segments: - * segment = *pchar - * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - * pct-encoded = "%" HEXDIG HEXDIG - * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" - * / "*" / "+" / "," / ";" / "=" - */ - function encodeUriSegment(val) { - return encodeUriQuery(val, true). - replace(/%26/gi, '&'). - replace(/%3D/gi, '='). - replace(/%2B/gi, '+'); - } - - - /** - * This method is intended for encoding *key* or *value* parts of query component. We need a custom - * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be - * encoded per http://tools.ietf.org/html/rfc3986: - * query = *( pchar / "/" / "?" ) - * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * pct-encoded = "%" HEXDIG HEXDIG - * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" - * / "*" / "+" / "," / ";" / "=" - */ - function encodeUriQuery(val, pctEncodeSpaces) { - return encodeURIComponent(val). - replace(/%40/gi, '@'). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); - } - - function Route(template, defaults) { - this.template = template = template + '#'; - this.defaults = defaults || {}; - var urlParams = this.urlParams = {}; - forEach(template.split(/\W/), function(param){ - if (param && (new RegExp("(^|[^\\\\]):" + param + "\\W").test(template))) { - urlParams[param] = true; - } - }); - this.template = template.replace(/\\:/g, ':'); - } - - Route.prototype = { - url: function(params) { - var self = this, - url = this.template, - val, - encodedVal; - - params = params || {}; - forEach(this.urlParams, function(_, urlParam){ - val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam]; - if (angular.isDefined(val) && val !== null) { - encodedVal = encodeUriSegment(val); - url = url.replace(new RegExp(":" + urlParam + "(\\W)", "g"), encodedVal + "$1"); - } else { - url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W)", "g"), function(match, - leadingSlashes, tail) { - if (tail.charAt(0) == '/') { - return tail; - } else { - return leadingSlashes + tail; - } - }); - } - }); - url = url.replace(/\/?#$/, ''); - var query = []; - forEach(params, function(value, key){ - if (!self.urlParams[key]) { - query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value)); - } - }); - query.sort(); - 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, actionParams){ - var ids = {}; - actionParams = extend({}, paramDefaults, actionParams); - forEach(actionParams, 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) { - action.method = angular.uppercase(action.method); - var hasBody = action.method == 'POST' || action.method == 'PUT' || action.method == 'PATCH'; - 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 (hasBody) 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.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 = hasBody ? this : undefined; - Resource[name].call(this, params, data, success, error); - }; - }); - - Resource.bind = function(additionalParamDefaults){ - return ResourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); - }; - - return Resource; - } - - return ResourceFactory; - }]); - - -})(window, window.angular); diff --git a/dist/dependencies/angular.js b/dist/dependencies/angular.js deleted file mode 100644 index 140682e4..00000000 --- a/dist/dependencies/angular.js +++ /dev/null @@ -1,17902 +0,0 @@ -/** - * @license AngularJS v1.2.0rc1 - * (c) 2010-2012 Google, Inc. http://angularjs.org - * License: MIT - */ -(function(window, document, undefined) {'use strict'; - -/** - * @description - * - * This object provides a utility for producing rich Error messages within - * Angular. It can be called as follows: - * - * var exampleMinErr = minErr('example'); - * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); - * - * The above creates an instance of minErr in the example namespace. The - * resulting error will have a namespaced error code of example.one. The - * resulting error will replace {0} with the value of foo, and {1} with the - * value of bar. The object is not restricted in the number of arguments it can - * take. - * - * If fewer arguments are specified than necessary for interpolation, the extra - * interpolation markers will be preserved in the final string. - * - * Since data will be parsed statically during a build step, some restrictions - * are applied with respect to how minErr instances are created and called. - * Instances should have names of the form namespaceMinErr for a minErr created - * using minErr('namespace') . Error codes, namespaces and template strings - * should all be static strings, not variables or general expressions. - * - * @param {string} module The namespace to use for the new minErr instance. - * @returns {function(string, string, ...): Error} instance - */ - -function minErr(module) { - return function () { - var prefix = '[' + (module ? module + ':' : '') + arguments[0] + '] ', - template = arguments[1], - templateArgs = arguments, - message; - - message = prefix + template.replace(/\{\d+\}/g, function (match) { - var index = +match.slice(1, -1), arg; - - if (index + 2 < templateArgs.length) { - arg = templateArgs[index + 2]; - if (isFunction(arg)) { - return arg.toString().replace(/ ?\{[\s\S]*$/, ''); - } else if (isUndefined(arg)) { - return 'undefined'; - } else if (!isString(arg)) { - return toJson(arg); - } - return arg; - } - return match; - }); - - return new Error(message); - }; -} - -//////////////////////////////////// - -/** - * hasOwnProperty may be overwritten by a property of the same name, or entirely - * absent from an object that does not inherit Object.prototype; this copy is - * used instead - */ -var hasOwnPropertyFn = Object.prototype.hasOwnProperty; -var hasOwnPropertyLocal = function(obj, key) { - return hasOwnPropertyFn.call(obj, key); -}; - -/** - * @ngdoc function - * @name angular.lowercase - * @function - * - * @description Converts the specified string to lowercase. - * @param {string} string String to be converted to lowercase. - * @returns {string} Lowercased string. - */ -var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;}; - - -/** - * @ngdoc function - * @name angular.uppercase - * @function - * - * @description Converts the specified string to uppercase. - * @param {string} string String to be converted to uppercase. - * @returns {string} Uppercased string. - */ -var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;}; - - -var manualLowercase = function(s) { - return isString(s) - ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);}) - : s; -}; -var manualUppercase = function(s) { - return isString(s) - ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);}) - : s; -}; - - -// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish -// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods -// with correct but slower alternatives. -if ('i' !== 'I'.toLowerCase()) { - lowercase = manualLowercase; - uppercase = manualUppercase; -} - - -var /** holds major version number for IE or NaN for real browsers */ - msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]), - jqLite, // delay binding since jQuery could be loaded after us. - jQuery, // delay binding - slice = [].slice, - push = [].push, - toString = Object.prototype.toString, - ngMinErr = minErr('ng'), - - - _angular = window.angular, - /** @name angular */ - angular = window.angular || (window.angular = {}), - angularModule, - nodeName_, - uid = ['0', '0', '0']; - -/** - * @private - * @param {*} obj - * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, ...) - */ -function isArrayLike(obj) { - if (obj == null || isWindow(obj)) { - return false; - } - - var length = obj.length; - - if (obj.nodeType === 1 && length) { - return true; - } - - return isArray(obj) || !isFunction(obj) && ( - length === 0 || typeof length === "number" && length > 0 && (length - 1) in obj - ); -} - -/** - * @ngdoc function - * @name angular.forEach - * @function - * - * @description - * Invokes the `iterator` function once for each item in `obj` collection, which can be either an - * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value` - * is the value of an object property or an array element and `key` is the object property key or - * array element index. Specifying a `context` for the function is optional. - * - * Note: this function was previously known as `angular.foreach`. - * -
-     var values = {name: 'misko', gender: 'male'};
-     var log = [];
-     angular.forEach(values, function(value, key){
-       this.push(key + ': ' + value);
-     }, log);
-     expect(log).toEqual(['name: misko', 'gender:male']);
-   
- * - * @param {Object|Array} obj Object to iterate over. - * @param {Function} iterator Iterator function. - * @param {Object=} context Object to become context (`this`) for the iterator function. - * @returns {Object|Array} Reference to `obj`. - */ -function forEach(obj, iterator, context) { - var key; - if (obj) { - if (isFunction(obj)){ - for (key in obj) { - if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) { - iterator.call(context, obj[key], key); - } - } - } else if (obj.forEach && obj.forEach !== forEach) { - obj.forEach(iterator, context); - } else if (isArrayLike(obj)) { - for (key = 0; key < obj.length; key++) - iterator.call(context, obj[key], key); - } else { - for (key in obj) { - if (obj.hasOwnProperty(key)) { - iterator.call(context, obj[key], key); - } - } - } - } - return obj; -} - -function sortedKeys(obj) { - var keys = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - keys.push(key); - } - } - return keys.sort(); -} - -function forEachSorted(obj, iterator, context) { - var keys = sortedKeys(obj); - for ( var i = 0; i < keys.length; i++) { - iterator.call(context, obj[keys[i]], keys[i]); - } - return keys; -} - - -/** - * when using forEach the params are value, key, but it is often useful to have key, value. - * @param {function(string, *)} iteratorFn - * @returns {function(*, string)} - */ -function reverseParams(iteratorFn) { - return function(value, key) { iteratorFn(key, value) }; -} - -/** - * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric - * characters such as '012ABC'. The reason why we are not using simply a number counter is that - * the number string gets longer over time, and it can also overflow, where as the nextId - * will grow much slower, it is a string, and it will never overflow. - * - * @returns an unique alpha-numeric string - */ -function nextUid() { - var index = uid.length; - var digit; - - while(index) { - index--; - digit = uid[index].charCodeAt(0); - if (digit == 57 /*'9'*/) { - uid[index] = 'A'; - return uid.join(''); - } - if (digit == 90 /*'Z'*/) { - uid[index] = '0'; - } else { - uid[index] = String.fromCharCode(digit + 1); - return uid.join(''); - } - } - uid.unshift('0'); - return uid.join(''); -} - - -/** - * Set or clear the hashkey for an object. - * @param obj object - * @param h the hashkey (!truthy to delete the hashkey) - */ -function setHashKey(obj, h) { - if (h) { - obj.$$hashKey = h; - } - else { - delete obj.$$hashKey; - } -} - -/** - * @ngdoc function - * @name angular.extend - * @function - * - * @description - * Extends the destination object `dst` by copying all of the properties from the `src` object(s) - * to `dst`. You can specify multiple `src` objects. - * - * @param {Object} dst Destination object. - * @param {...Object} src Source object(s). - * @returns {Object} Reference to `dst`. - */ -function extend(dst) { - var h = dst.$$hashKey; - forEach(arguments, function(obj){ - if (obj !== dst) { - forEach(obj, function(value, key){ - dst[key] = value; - }); - } - }); - - setHashKey(dst,h); - return dst; -} - -function int(str) { - return parseInt(str, 10); -} - - -function inherit(parent, extra) { - return extend(new (extend(function() {}, {prototype:parent}))(), extra); -} - -/** - * @ngdoc function - * @name angular.noop - * @function - * - * @description - * A function that performs no operations. This function can be useful when writing code in the - * functional style. -
-     function foo(callback) {
-       var result = calculateResult();
-       (callback || angular.noop)(result);
-     }
-   
- */ -function noop() {} -noop.$inject = []; - - -/** - * @ngdoc function - * @name angular.identity - * @function - * - * @description - * A function that returns its first argument. This function is useful when writing code in the - * functional style. - * -
-     function transformer(transformationFn, value) {
-       return (transformationFn || angular.identity)(value);
-     };
-   
- */ -function identity($) {return $;} -identity.$inject = []; - - -function valueFn(value) {return function() {return value;};} - -/** - * @ngdoc function - * @name angular.isUndefined - * @function - * - * @description - * Determines if a reference is undefined. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is undefined. - */ -function isUndefined(value){return typeof value == 'undefined';} - - -/** - * @ngdoc function - * @name angular.isDefined - * @function - * - * @description - * Determines if a reference is defined. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is defined. - */ -function isDefined(value){return typeof value != 'undefined';} - - -/** - * @ngdoc function - * @name angular.isObject - * @function - * - * @description - * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not - * considered to be objects. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is an `Object` but not `null`. - */ -function isObject(value){return value != null && typeof value == 'object';} - - -/** - * @ngdoc function - * @name angular.isString - * @function - * - * @description - * Determines if a reference is a `String`. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is a `String`. - */ -function isString(value){return typeof value == 'string';} - - -/** - * @ngdoc function - * @name angular.isNumber - * @function - * - * @description - * Determines if a reference is a `Number`. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is a `Number`. - */ -function isNumber(value){return typeof value == 'number';} - - -/** - * @ngdoc function - * @name angular.isDate - * @function - * - * @description - * Determines if a value is a date. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is a `Date`. - */ -function isDate(value){ - return toString.apply(value) == '[object Date]'; -} - - -/** - * @ngdoc function - * @name angular.isArray - * @function - * - * @description - * Determines if a reference is an `Array`. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is an `Array`. - */ -function isArray(value) { - return toString.apply(value) == '[object Array]'; -} - - -/** - * @ngdoc function - * @name angular.isFunction - * @function - * - * @description - * Determines if a reference is a `Function`. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is a `Function`. - */ -function isFunction(value){return typeof value == 'function';} - - -/** - * Determines if a value is a regular expression object. - * - * @private - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is a `RegExp`. - */ -function isRegExp(value) { - return toString.apply(value) == '[object RegExp]'; -} - - -/** - * Checks if `obj` is a window object. - * - * @private - * @param {*} obj Object to check - * @returns {boolean} True if `obj` is a window obj. - */ -function isWindow(obj) { - return obj && obj.document && obj.location && obj.alert && obj.setInterval; -} - - -function isScope(obj) { - return obj && obj.$evalAsync && obj.$watch; -} - - -function isFile(obj) { - return toString.apply(obj) === '[object File]'; -} - - -function isBoolean(value) { - return typeof value == 'boolean'; -} - - -var trim = (function() { - // native trim is way faster: http://jsperf.com/angular-trim-test - // but IE doesn't have it... :-( - // TODO: we should move this into IE/ES5 polyfill - if (!String.prototype.trim) { - return function(value) { - return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; - }; - } - return function(value) { - return isString(value) ? value.trim() : value; - }; -})(); - - -/** - * @ngdoc function - * @name angular.isElement - * @function - * - * @description - * Determines if a reference is a DOM element (or wrapped jQuery element). - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). - */ -function isElement(node) { - return node && - (node.nodeName // we are a direct element - || (node.on && node.find)); // we have an on and find method part of jQuery API -} - -/** - * @param str 'key1,key2,...' - * @returns {object} in the form of {key1:true, key2:true, ...} - */ -function makeMap(str){ - var obj = {}, items = str.split(","), i; - for ( i = 0; i < items.length; i++ ) - obj[ items[i] ] = true; - return obj; -} - - -if (msie < 9) { - nodeName_ = function(element) { - element = element.nodeName ? element : element[0]; - return (element.scopeName && element.scopeName != 'HTML') - ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; - }; -} else { - nodeName_ = function(element) { - return element.nodeName ? element.nodeName : element[0].nodeName; - }; -} - - -function map(obj, iterator, context) { - var results = []; - forEach(obj, function(value, index, list) { - results.push(iterator.call(context, value, index, list)); - }); - return results; -} - - -/** - * @description - * Determines the number of elements in an array, the number of properties an object has, or - * the length of a string. - * - * Note: This function is used to augment the Object type in Angular expressions. See - * {@link angular.Object} for more information about Angular arrays. - * - * @param {Object|Array|string} obj Object, array, or string to inspect. - * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object - * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array. - */ -function size(obj, ownPropsOnly) { - var size = 0, key; - - if (isArray(obj) || isString(obj)) { - return obj.length; - } else if (isObject(obj)){ - for (key in obj) - if (!ownPropsOnly || obj.hasOwnProperty(key)) - size++; - } - - return size; -} - - -function includes(array, obj) { - return indexOf(array, obj) != -1; -} - -function indexOf(array, obj) { - if (array.indexOf) return array.indexOf(obj); - - for ( var i = 0; i < array.length; i++) { - if (obj === array[i]) return i; - } - return -1; -} - -function arrayRemove(array, value) { - var index = indexOf(array, value); - if (index >=0) - array.splice(index, 1); - return value; -} - -function isLeafNode (node) { - if (node) { - switch (node.nodeName) { - case "OPTION": - case "PRE": - case "TITLE": - return true; - } - } - return false; -} - -/** - * @ngdoc function - * @name angular.copy - * @function - * - * @description - * Creates a deep copy of `source`, which should be an object or an array. - * - * * If no destination is supplied, a copy of the object or array is created. - * * If a destination is provided, all of its elements (for array) or properties (for objects) - * are deleted and then all elements/properties from the source are copied to it. - * * If `source` is not an object or array, `source` is returned. - * - * Note: this function is used to augment the Object type in Angular expressions. See - * {@link ng.$filter} for more information about Angular arrays. - * - * @param {*} source The source that will be used to make a copy. - * Can be any type, including primitives, `null`, and `undefined`. - * @param {(Object|Array)=} destination Destination into which the source is copied. If - * provided, must be of the same type as `source`. - * @returns {*} The copy or updated `destination`, if `destination` was specified. - */ -function copy(source, destination){ - if (isWindow(source) || isScope(source)) { - throw ngMinErr('cpws', "Can't copy! Making copies of Window or Scope instances is not supported."); - } - - if (!destination) { - destination = source; - if (source) { - if (isArray(source)) { - destination = copy(source, []); - } else if (isDate(source)) { - destination = new Date(source.getTime()); - } else if (isRegExp(source)) { - destination = new RegExp(source.source); - } else if (isObject(source)) { - destination = copy(source, {}); - } - } - } else { - if (source === destination) throw ngMinErr('cpi', "Can't copy! Source and destination are identical."); - if (isArray(source)) { - destination.length = 0; - for ( var i = 0; i < source.length; i++) { - destination.push(copy(source[i])); - } - } else { - var h = destination.$$hashKey; - forEach(destination, function(value, key){ - delete destination[key]; - }); - for ( var key in source) { - destination[key] = copy(source[key]); - } - setHashKey(destination,h); - } - } - return destination; -} - -/** - * Create a shallow copy of an object - */ -function shallowCopy(src, dst) { - dst = dst || {}; - - for(var key in src) { - if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') { - dst[key] = src[key]; - } - } - - return dst; -} - - -/** - * @ngdoc function - * @name angular.equals - * @function - * - * @description - * Determines if two objects or two values are equivalent. Supports value types, regular expressions, arrays and - * objects. - * - * Two objects or values are considered equivalent if at least one of the following is true: - * - * * Both objects or values pass `===` comparison. - * * Both objects or values are of the same type and all of their properties pass `===` comparison. - * * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal) - * * Both values represent the same regular expression (In JavasScript, - * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual - * representation matches). - * - * During a property comparison, properties of `function` type and properties with names - * that begin with `$` are ignored. - * - * Scope and DOMWindow objects are being compared only by identify (`===`). - * - * @param {*} o1 Object or value to compare. - * @param {*} o2 Object or value to compare. - * @returns {boolean} True if arguments are equal. - */ -function equals(o1, o2) { - if (o1 === o2) return true; - if (o1 === null || o2 === null) return false; - if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN - var t1 = typeof o1, t2 = typeof o2, length, key, keySet; - if (t1 == t2) { - if (t1 == 'object') { - if (isArray(o1)) { - if (!isArray(o2)) return false; - if ((length = o1.length) == o2.length) { - for(key=0; key 2 ? sliceArgs(arguments, 2) : []; - if (isFunction(fn) && !(fn instanceof RegExp)) { - return curryArgs.length - ? function() { - return arguments.length - ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) - : fn.apply(self, curryArgs); - } - : function() { - return arguments.length - ? fn.apply(self, arguments) - : fn.call(self); - }; - } else { - // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) - return fn; - } -} - - -function toJsonReplacer(key, value) { - var val = value; - - if (/^\$+/.test(key)) { - val = undefined; - } else if (isWindow(value)) { - val = '$WINDOW'; - } else if (value && document === value) { - val = '$DOCUMENT'; - } else if (isScope(value)) { - val = '$SCOPE'; - } - - return val; -} - - -/** - * @ngdoc function - * @name angular.toJson - * @function - * - * @description - * Serializes input into a JSON-formatted string. Properties with leading $ characters will be - * stripped since angular uses this notation internally. - * - * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. - * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. - * @returns {string|undefined} JSON-ified string representing `obj`. - */ -function toJson(obj, pretty) { - if (typeof obj === 'undefined') return undefined; - return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); -} - - -/** - * @ngdoc function - * @name angular.fromJson - * @function - * - * @description - * Deserializes a JSON string. - * - * @param {string} json JSON string to deserialize. - * @returns {Object|Array|Date|string|number} Deserialized thingy. - */ -function fromJson(json) { - return isString(json) - ? JSON.parse(json) - : json; -} - - -function toBoolean(value) { - if (value && value.length !== 0) { - var v = lowercase("" + value); - value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); - } else { - value = false; - } - return value; -} - -/** - * @returns {string} Returns the string representation of the element. - */ -function startingTag(element) { - element = jqLite(element).clone(); - try { - // turns out IE does not let you set .html() on elements which - // are not allowed to have children. So we just ignore it. - element.html(''); - } catch(e) {} - // As Per DOM Standards - var TEXT_NODE = 3; - var elemHtml = jqLite('
').append(element).html(); - try { - return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) : - elemHtml. - match(/^(<[^>]+>)/)[1]. - replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); }); - } catch(e) { - return lowercase(elemHtml); - } - -} - - -///////////////////////////////////////////////// - -/** - * Tries to decode the URI component without throwing an exception. - * - * @private - * @param str value potential URI component to check. - * @returns {boolean} True if `value` can be decoded - * with the decodeURIComponent function. - */ -function tryDecodeURIComponent(value) { - try { - return decodeURIComponent(value); - } catch(e) { - // Ignore any invalid uri component - } -} - - -/** - * Parses an escaped url query string into key-value pairs. - * @returns Object.<(string|boolean)> - */ -function parseKeyValue(/**string*/keyValue) { - var obj = {}, key_value, key; - forEach((keyValue || "").split('&'), function(keyValue){ - if ( keyValue ) { - key_value = keyValue.split('='); - key = tryDecodeURIComponent(key_value[0]); - if ( isDefined(key) ) { - var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; - if (!obj[key]) { - obj[key] = val; - } else if(isArray(obj[key])) { - obj[key].push(val); - } else { - obj[key] = [obj[key],val]; - } - } - } - }); - return obj; -} - -function toKeyValue(obj) { - var parts = []; - forEach(obj, function(value, key) { - if (isArray(value)) { - forEach(value, function(arrayValue) { - parts.push(encodeUriQuery(key, true) + (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true))); - }); - } else { - parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true))); - } - }); - return parts.length ? parts.join('&') : ''; -} - - -/** - * We need our custom method because encodeURIComponent is too aggressive and doesn't follow - * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path - * segments: - * segment = *pchar - * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - * pct-encoded = "%" HEXDIG HEXDIG - * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" - * / "*" / "+" / "," / ";" / "=" - */ -function encodeUriSegment(val) { - return encodeUriQuery(val, true). - replace(/%26/gi, '&'). - replace(/%3D/gi, '='). - replace(/%2B/gi, '+'); -} - - -/** - * This method is intended for encoding *key* or *value* parts of query component. We need a custom - * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be - * encoded per http://tools.ietf.org/html/rfc3986: - * query = *( pchar / "/" / "?" ) - * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * pct-encoded = "%" HEXDIG HEXDIG - * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" - * / "*" / "+" / "," / ";" / "=" - */ -function encodeUriQuery(val, pctEncodeSpaces) { - return encodeURIComponent(val). - replace(/%40/gi, '@'). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); -} - - -/** - * @ngdoc directive - * @name ng.directive:ngApp - * - * @element ANY - * @param {angular.Module} ngApp an optional application - * {@link angular.module module} name to load. - * - * @description - * - * Use this directive to auto-bootstrap an application. Only - * one ngApp directive can be used per HTML document. The directive - * designates the root of the application and is typically placed - * at the root of the page. - * - * The first ngApp found in the document will be auto-bootstrapped. To use multiple applications in an - * HTML document you must manually bootstrap them using {@link angular.bootstrap}. - * Applications cannot be nested. - * - * In the example below if the `ngApp` directive would not be placed - * on the `html` element then the document would not be compiled - * and the `{{ 1+2 }}` would not be resolved to `3`. - * - * `ngApp` is the easiest way to bootstrap an application. - * - - - I can add: 1 + 2 = {{ 1+2 }} - - - * - */ -function angularInit(element, bootstrap) { - var elements = [element], - appElement, - module, - names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'], - NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/; - - function append(element) { - element && elements.push(element); - } - - forEach(names, function(name) { - names[name] = true; - append(document.getElementById(name)); - name = name.replace(':', '\\:'); - if (element.querySelectorAll) { - forEach(element.querySelectorAll('.' + name), append); - forEach(element.querySelectorAll('.' + name + '\\:'), append); - forEach(element.querySelectorAll('[' + name + ']'), append); - } - }); - - forEach(elements, function(element) { - if (!appElement) { - var className = ' ' + element.className + ' '; - var match = NG_APP_CLASS_REGEXP.exec(className); - if (match) { - appElement = element; - module = (match[2] || '').replace(/\s+/g, ','); - } else { - forEach(element.attributes, function(attr) { - if (!appElement && names[attr.name]) { - appElement = element; - module = attr.value; - } - }); - } - } - }); - if (appElement) { - bootstrap(appElement, module ? [module] : []); - } -} - -/** - * @ngdoc function - * @name angular.bootstrap - * @description - * Use this function to manually start up angular application. - * - * See: {@link guide/bootstrap Bootstrap} - * - * Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually. - * They must use {@link api/ng.directive:ngApp ngApp}. - * - * @param {Element} element DOM element which is the root of angular application. - * @param {Array=} modules an array of module declarations. See: {@link angular.module modules} - * @returns {AUTO.$injector} Returns the newly created injector for this app. - */ -function bootstrap(element, modules) { - var doBootstrap = function() { - element = jqLite(element); - - if (element.injector()) { - var tag = (element[0] === document) ? 'document' : startingTag(element); - throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag); - } - - modules = modules || []; - modules.unshift(['$provide', function($provide) { - $provide.value('$rootElement', element); - }]); - modules.unshift('ng'); - var injector = createInjector(modules); - injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate', - function(scope, element, compile, injector, animate) { - scope.$apply(function() { - element.data('$injector', injector); - compile(element)(scope); - }); - animate.enabled(true); - }] - ); - return injector; - }; - - var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; - - if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { - return doBootstrap(); - } - - window.name = window.name.replace(NG_DEFER_BOOTSTRAP, ''); - angular.resumeBootstrap = function(extraModules) { - forEach(extraModules, function(module) { - modules.push(module); - }); - doBootstrap(); - }; -} - -var SNAKE_CASE_REGEXP = /[A-Z]/g; -function snake_case(name, separator){ - separator = separator || '_'; - return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { - return (pos ? separator : '') + letter.toLowerCase(); - }); -} - -function bindJQuery() { - // bind to jQuery if present; - jQuery = window.jQuery; - // reset to jQuery or default to us. - if (jQuery) { - jqLite = jQuery; - extend(jQuery.fn, { - scope: JQLitePrototype.scope, - controller: JQLitePrototype.controller, - injector: JQLitePrototype.injector, - inheritedData: JQLitePrototype.inheritedData - }); - // Method signature: JQLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) - JQLitePatchJQueryRemove('remove', true, true, false); - JQLitePatchJQueryRemove('empty', false, false, false); - JQLitePatchJQueryRemove('html', false, false, true); - } else { - jqLite = JQLite; - } - angular.element = jqLite; -} - -/** - * throw error if the argument is falsy. - */ -function assertArg(arg, name, reason) { - if (!arg) { - throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required")); - } - return arg; -} - -function assertArgFn(arg, name, acceptArrayAnnotation) { - if (acceptArrayAnnotation && isArray(arg)) { - arg = arg[arg.length - 1]; - } - - assertArg(isFunction(arg), name, 'not a function, got ' + - (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg)); - return arg; -} - -/** - * Return the value accessible from the object by path. Any undefined traversals are ignored - * @param {Object} obj starting object - * @param {string} path path to traverse - * @param {boolean=true} bindFnToScope - * @returns value as accessible by path - */ -//TODO(misko): this function needs to be removed -function getter(obj, path, bindFnToScope) { - if (!path) return obj; - var keys = path.split('.'); - var key; - var lastInstance = obj; - var len = keys.length; - - for (var i = 0; i < len; i++) { - key = keys[i]; - if (obj) { - obj = (lastInstance = obj)[key]; - } - } - if (!bindFnToScope && isFunction(obj)) { - return bind(lastInstance, obj); - } - return obj; -} - -/** - * @ngdoc interface - * @name angular.Module - * @description - * - * Interface for configuring angular {@link angular.module modules}. - */ - -function setupModuleLoader(window) { - - function ensure(obj, name, factory) { - return obj[name] || (obj[name] = factory()); - } - - return ensure(ensure(window, 'angular', Object), 'module', function() { - /** @type {Object.} */ - var modules = {}; - - /** - * @ngdoc function - * @name angular.module - * @description - * - * The `angular.module` is a global place for creating and registering Angular modules. All - * modules (angular core or 3rd party) that should be available to an application must be - * registered using this mechanism. - * - * - * # Module - * - * A module is a collection of services, directives, filters, and configuration information. - * `angular.module` is used to configure the {@link AUTO.$injector $injector}. - * - *
-     * // Create a new module
-     * var myModule = angular.module('myModule', []);
-     *
-     * // register a new service
-     * myModule.value('appName', 'MyCoolApp');
-     *
-     * // configure existing services inside initialization blocks.
-     * myModule.config(function($locationProvider) {
-     *   // Configure existing providers
-     *   $locationProvider.hashPrefix('!');
-     * });
-     * 
- * - * Then you can create an injector and load your modules like this: - * - *
-     * var injector = angular.injector(['ng', 'MyModule'])
-     * 
- * - * However it's more likely that you'll just use - * {@link ng.directive:ngApp ngApp} or - * {@link angular.bootstrap} to simplify this process for you. - * - * @param {!string} name The name of the module to create or retrieve. - * @param {Array.=} requires If specified then new module is being created. If unspecified then the - * the module is being retrieved for further configuration. - * @param {Function} configFn Optional configuration function for the module. Same as - * {@link angular.Module#config Module#config()}. - * @returns {module} new module with the {@link angular.Module} api. - */ - return function module(name, requires, configFn) { - if (requires && modules.hasOwnProperty(name)) { - modules[name] = null; - } - return ensure(modules, name, function() { - if (!requires) { - throw minErr('$injector')('nomod', "Module '{0}' is not available! You either misspelled the module name " + - "or forgot to load it. If registering a module ensure that you specify the dependencies as the second " + - "argument.", name); - } - - /** @type {!Array.>} */ - var invokeQueue = []; - - /** @type {!Array.} */ - var runBlocks = []; - - var config = invokeLater('$injector', 'invoke'); - - /** @type {angular.Module} */ - var moduleInstance = { - // Private state - _invokeQueue: invokeQueue, - _runBlocks: runBlocks, - - /** - * @ngdoc property - * @name angular.Module#requires - * @propertyOf angular.Module - * @returns {Array.} List of module names which must be loaded before this module. - * @description - * Holds the list of modules which the injector will load before the current module is loaded. - */ - requires: requires, - - /** - * @ngdoc property - * @name angular.Module#name - * @propertyOf angular.Module - * @returns {string} Name of the module. - * @description - */ - name: name, - - - /** - * @ngdoc method - * @name angular.Module#provider - * @methodOf angular.Module - * @param {string} name service name - * @param {Function} providerType Construction function for creating new instance of the service. - * @description - * See {@link AUTO.$provide#provider $provide.provider()}. - */ - provider: invokeLater('$provide', 'provider'), - - /** - * @ngdoc method - * @name angular.Module#factory - * @methodOf angular.Module - * @param {string} name service name - * @param {Function} providerFunction Function for creating new instance of the service. - * @description - * See {@link AUTO.$provide#factory $provide.factory()}. - */ - factory: invokeLater('$provide', 'factory'), - - /** - * @ngdoc method - * @name angular.Module#service - * @methodOf angular.Module - * @param {string} name service name - * @param {Function} constructor A constructor function that will be instantiated. - * @description - * See {@link AUTO.$provide#service $provide.service()}. - */ - service: invokeLater('$provide', 'service'), - - /** - * @ngdoc method - * @name angular.Module#value - * @methodOf angular.Module - * @param {string} name service name - * @param {*} object Service instance object. - * @description - * See {@link AUTO.$provide#value $provide.value()}. - */ - value: invokeLater('$provide', 'value'), - - /** - * @ngdoc method - * @name angular.Module#constant - * @methodOf angular.Module - * @param {string} name constant name - * @param {*} object Constant value. - * @description - * Because the constant are fixed, they get applied before other provide methods. - * See {@link AUTO.$provide#constant $provide.constant()}. - */ - constant: invokeLater('$provide', 'constant', 'unshift'), - - /** - * @ngdoc method - * @name angular.Module#animation - * @methodOf angular.Module - * @param {string} name animation name - * @param {Function} animationFactory Factory function for creating new instance of an animation. - * @description - * - * **NOTE**: animations are take effect only if the **ngAnimate** module is loaded. - * - * - * Defines an animation hook that can be later used with {@link ngAnimate.$animate $animate} service and - * directives that use this service. - * - *
-           * module.animation('.animation-name', function($inject1, $inject2) {
-           *   return {
-           *     eventName : function(element, done) {
-           *       //code to run the animation
-           *       //once complete, then run done()
-           *       return function cancellationFunction(element) {
-           *         //code to cancel the animation
-           *       }
-           *     }
-           *   }
-           * })
-           * 
- * - * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and - * {@link ngAnimate ngAnimate module} for more information. - */ - animation: invokeLater('$animateProvider', 'register'), - - /** - * @ngdoc method - * @name angular.Module#filter - * @methodOf angular.Module - * @param {string} name Filter name. - * @param {Function} filterFactory Factory function for creating new instance of filter. - * @description - * See {@link ng.$filterProvider#register $filterProvider.register()}. - */ - filter: invokeLater('$filterProvider', 'register'), - - /** - * @ngdoc method - * @name angular.Module#controller - * @methodOf angular.Module - * @param {string} name Controller name. - * @param {Function} constructor Controller constructor function. - * @description - * See {@link ng.$controllerProvider#register $controllerProvider.register()}. - */ - controller: invokeLater('$controllerProvider', 'register'), - - /** - * @ngdoc method - * @name angular.Module#directive - * @methodOf angular.Module - * @param {string} name directive name - * @param {Function} directiveFactory Factory function for creating new instance of - * directives. - * @description - * See {@link ng.$compileProvider#directive $compileProvider.directive()}. - */ - directive: invokeLater('$compileProvider', 'directive'), - - /** - * @ngdoc method - * @name angular.Module#config - * @methodOf angular.Module - * @param {Function} configFn Execute this function on module load. Useful for service - * configuration. - * @description - * Use this method to register work which needs to be performed on module loading. - */ - config: config, - - /** - * @ngdoc method - * @name angular.Module#run - * @methodOf angular.Module - * @param {Function} initializationFn Execute this function after injector creation. - * Useful for application initialization. - * @description - * Use this method to register work which should be performed when the injector is done - * loading all modules. - */ - run: function(block) { - runBlocks.push(block); - return this; - } - }; - - if (configFn) { - config(configFn); - } - - return moduleInstance; - - /** - * @param {string} provider - * @param {string} method - * @param {String=} insertMethod - * @returns {angular.Module} - */ - function invokeLater(provider, method, insertMethod) { - return function() { - invokeQueue[insertMethod || 'push']([provider, method, arguments]); - return moduleInstance; - } - } - }); - }; - }); - -} - -/** - * @ngdoc property - * @name angular.version - * @description - * An object that contains information about the current AngularJS version. This object has the - * following properties: - * - * - `full` – `{string}` – Full version string, such as "0.9.18". - * - `major` – `{number}` – Major version number, such as "0". - * - `minor` – `{number}` – Minor version number, such as "9". - * - `dot` – `{number}` – Dot version number, such as "18". - * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". - */ -var version = { - full: '1.2.0rc1', // all of these placeholder strings will be replaced by grunt's - major: 1, // package task - minor: 2, - dot: 0, - codeName: 'spooky-giraffe' -}; - - -function publishExternalAPI(angular){ - extend(angular, { - 'bootstrap': bootstrap, - 'copy': copy, - 'extend': extend, - 'equals': equals, - 'element': jqLite, - 'forEach': forEach, - 'injector': createInjector, - 'noop':noop, - 'bind':bind, - 'toJson': toJson, - 'fromJson': fromJson, - 'identity':identity, - 'isUndefined': isUndefined, - 'isDefined': isDefined, - 'isString': isString, - 'isFunction': isFunction, - 'isObject': isObject, - 'isNumber': isNumber, - 'isElement': isElement, - 'isArray': isArray, - '$$minErr': minErr, - 'version': version, - 'isDate': isDate, - 'lowercase': lowercase, - 'uppercase': uppercase, - 'callbacks': {counter: 0} - }); - - angularModule = setupModuleLoader(window); - try { - angularModule('ngLocale'); - } catch (e) { - angularModule('ngLocale', []).provider('$locale', $LocaleProvider); - } - - angularModule('ng', ['ngLocale'], ['$provide', - function ngModule($provide) { - $provide.provider('$compile', $CompileProvider). - directive({ - a: htmlAnchorDirective, - input: inputDirective, - textarea: inputDirective, - form: formDirective, - script: scriptDirective, - select: selectDirective, - style: styleDirective, - option: optionDirective, - ngBind: ngBindDirective, - ngBindHtml: ngBindHtmlDirective, - ngBindTemplate: ngBindTemplateDirective, - ngClass: ngClassDirective, - ngClassEven: ngClassEvenDirective, - ngClassOdd: ngClassOddDirective, - ngCsp: ngCspDirective, - ngCloak: ngCloakDirective, - ngController: ngControllerDirective, - ngForm: ngFormDirective, - ngHide: ngHideDirective, - ngIf: ngIfDirective, - ngInclude: ngIncludeDirective, - ngInit: ngInitDirective, - ngNonBindable: ngNonBindableDirective, - ngPluralize: ngPluralizeDirective, - ngRepeat: ngRepeatDirective, - ngShow: ngShowDirective, - ngStyle: ngStyleDirective, - ngSwitch: ngSwitchDirective, - ngSwitchWhen: ngSwitchWhenDirective, - ngSwitchDefault: ngSwitchDefaultDirective, - ngOptions: ngOptionsDirective, - ngTransclude: ngTranscludeDirective, - ngModel: ngModelDirective, - ngList: ngListDirective, - ngChange: ngChangeDirective, - required: requiredDirective, - ngRequired: requiredDirective, - ngValue: ngValueDirective - }). - directive(ngAttributeAliasDirectives). - directive(ngEventDirectives); - $provide.provider({ - $anchorScroll: $AnchorScrollProvider, - $animate: $AnimateProvider, - $browser: $BrowserProvider, - $cacheFactory: $CacheFactoryProvider, - $controller: $ControllerProvider, - $document: $DocumentProvider, - $exceptionHandler: $ExceptionHandlerProvider, - $filter: $FilterProvider, - $interpolate: $InterpolateProvider, - $http: $HttpProvider, - $httpBackend: $HttpBackendProvider, - $location: $LocationProvider, - $log: $LogProvider, - $parse: $ParseProvider, - $rootScope: $RootScopeProvider, - $q: $QProvider, - $sce: $SceProvider, - $sceDelegate: $SceDelegateProvider, - $sniffer: $SnifferProvider, - $templateCache: $TemplateCacheProvider, - $timeout: $TimeoutProvider, - $window: $WindowProvider, - $$urlUtils: $$UrlUtilsProvider - }); - } - ]); -} - -////////////////////////////////// -//JQLite -////////////////////////////////// - -/** - * @ngdoc function - * @name angular.element - * @function - * - * @description - * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. - * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if - * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite - * implementation (commonly referred to as jqLite). - * - * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded` - * event fired. - * - * jqLite is a tiny, API-compatible subset of jQuery that allows - * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality - * within a very small footprint, so only a subset of the jQuery API - methods, arguments and - * invocation styles - are supported. - * - * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never - * raw DOM references. - * - * ## Angular's jqLite - * Angular's lite version of jQuery provides only the following jQuery methods: - * - * - [addClass()](http://api.jquery.com/addClass/) - * - [after()](http://api.jquery.com/after/) - * - [append()](http://api.jquery.com/append/) - * - [attr()](http://api.jquery.com/attr/) - * - [bind()](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData - * - [children()](http://api.jquery.com/children/) - Does not support selectors - * - [clone()](http://api.jquery.com/clone/) - * - [contents()](http://api.jquery.com/contents/) - * - [css()](http://api.jquery.com/css/) - * - [data()](http://api.jquery.com/data/) - * - [eq()](http://api.jquery.com/eq/) - * - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name - * - [hasClass()](http://api.jquery.com/hasClass/) - * - [html()](http://api.jquery.com/html/) - * - [next()](http://api.jquery.com/next/) - Does not support selectors - * - [on()](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData - * - [off()](http://api.jquery.com/off/) - Does not support namespaces or selectors - * - [parent()](http://api.jquery.com/parent/) - Does not support selectors - * - [prepend()](http://api.jquery.com/prepend/) - * - [prop()](http://api.jquery.com/prop/) - * - [ready()](http://api.jquery.com/ready/) - * - [remove()](http://api.jquery.com/remove/) - * - [removeAttr()](http://api.jquery.com/removeAttr/) - * - [removeClass()](http://api.jquery.com/removeClass/) - * - [removeData()](http://api.jquery.com/removeData/) - * - [replaceWith()](http://api.jquery.com/replaceWith/) - * - [text()](http://api.jquery.com/text/) - * - [toggleClass()](http://api.jquery.com/toggleClass/) - * - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers. - * - [unbind()](http://api.jquery.com/off/) - Does not support namespaces - * - [val()](http://api.jquery.com/val/) - * - [wrap()](http://api.jquery.com/wrap/) - * - * ## jQuery/jqLite Extras - * Angular also provides the following additional methods and events to both jQuery and jqLite: - * - * ### Events - * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event - * on all DOM nodes being removed. This can be used to clean up and 3rd party bindings to the DOM - * element before it is removed. - * ### Methods - * - `controller(name)` - retrieves the controller of the current element or its parent. By default - * retrieves controller associated with the `ngController` directive. If `name` is provided as - * camelCase directive name, then the controller for this directive will be retrieved (e.g. - * `'ngModel'`). - * - `injector()` - retrieves the injector of the current element or its parent. - * - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current - * element or its parent. - * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top - * parent element is reached. - * - * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. - * @returns {Object} jQuery object. - */ - -var jqCache = JQLite.cache = {}, - jqName = JQLite.expando = 'ng-' + new Date().getTime(), - jqId = 1, - addEventListenerFn = (window.document.addEventListener - ? function(element, type, fn) {element.addEventListener(type, fn, false);} - : function(element, type, fn) {element.attachEvent('on' + type, fn);}), - removeEventListenerFn = (window.document.removeEventListener - ? function(element, type, fn) {element.removeEventListener(type, fn, false); } - : function(element, type, fn) {element.detachEvent('on' + type, fn); }); - -function jqNextId() { return ++jqId; } - - -var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; -var MOZ_HACK_REGEXP = /^moz([A-Z])/; -var jqLiteMinErr = minErr('jqLite'); - -/** - * Converts snake_case to camelCase. - * Also there is special case for Moz prefix starting with upper case letter. - * @param name Name to normalize - */ -function camelCase(name) { - return name. - replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { - return offset ? letter.toUpperCase() : letter; - }). - replace(MOZ_HACK_REGEXP, 'Moz$1'); -} - -///////////////////////////////////////////// -// jQuery mutation patch -// -// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a -// $destroy event on all DOM nodes being removed. -// -///////////////////////////////////////////// - -function JQLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) { - var originalJqFn = jQuery.fn[name]; - originalJqFn = originalJqFn.$original || originalJqFn; - removePatch.$original = originalJqFn; - jQuery.fn[name] = removePatch; - - function removePatch(param) { - var list = filterElems && param ? [this.filter(param)] : [this], - fireEvent = dispatchThis, - set, setIndex, setLength, - element, childIndex, childLength, children; - - if (!getterIfNoArguments || param != null) { - while(list.length) { - set = list.shift(); - for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { - element = jqLite(set[setIndex]); - if (fireEvent) { - element.triggerHandler('$destroy'); - } else { - fireEvent = !fireEvent; - } - for(childIndex = 0, childLength = (children = element.children()).length; - childIndex < childLength; - childIndex++) { - list.push(jQuery(children[childIndex])); - } - } - } - } - return originalJqFn.apply(this, arguments); - } -} - -///////////////////////////////////////////// -function JQLite(element) { - if (element instanceof JQLite) { - return element; - } - if (!(this instanceof JQLite)) { - if (isString(element) && element.charAt(0) != '<') { - throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element'); - } - return new JQLite(element); - } - - if (isString(element)) { - var div = document.createElement('div'); - // Read about the NoScope elements here: - // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx - div.innerHTML = '
 
' + element; // IE insanity to make NoScope elements work! - div.removeChild(div.firstChild); // remove the superfluous div - JQLiteAddNodes(this, div.childNodes); - var fragment = jqLite(document.createDocumentFragment()); - fragment.append(this); // detach the elements from the temporary DOM div. - } else { - JQLiteAddNodes(this, element); - } -} - -function JQLiteClone(element) { - return element.cloneNode(true); -} - -function JQLiteDealoc(element){ - JQLiteRemoveData(element); - for ( var i = 0, children = element.childNodes || []; i < children.length; i++) { - JQLiteDealoc(children[i]); - } -} - -function JQLiteOff(element, type, fn, unsupported) { - if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument'); - - var events = JQLiteExpandoStore(element, 'events'), - handle = JQLiteExpandoStore(element, 'handle'); - - if (!handle) return; //no listeners registered - - if (isUndefined(type)) { - forEach(events, function(eventHandler, type) { - removeEventListenerFn(element, type, eventHandler); - delete events[type]; - }); - } else { - forEach(type.split(' '), function(type) { - if (isUndefined(fn)) { - removeEventListenerFn(element, type, events[type]); - delete events[type]; - } else { - arrayRemove(events[type] || [], fn); - } - }); - } -} - -function JQLiteRemoveData(element, name) { - var expandoId = element[jqName], - expandoStore = jqCache[expandoId]; - - if (expandoStore) { - if (name) { - delete jqCache[expandoId].data[name]; - return; - } - - if (expandoStore.handle) { - expandoStore.events.$destroy && expandoStore.handle({}, '$destroy'); - JQLiteOff(element); - } - delete jqCache[expandoId]; - element[jqName] = undefined; // ie does not allow deletion of attributes on elements. - } -} - -function JQLiteExpandoStore(element, key, value) { - var expandoId = element[jqName], - expandoStore = jqCache[expandoId || -1]; - - if (isDefined(value)) { - if (!expandoStore) { - element[jqName] = expandoId = jqNextId(); - expandoStore = jqCache[expandoId] = {}; - } - expandoStore[key] = value; - } else { - return expandoStore && expandoStore[key]; - } -} - -function JQLiteData(element, key, value) { - var data = JQLiteExpandoStore(element, 'data'), - isSetter = isDefined(value), - keyDefined = !isSetter && isDefined(key), - isSimpleGetter = keyDefined && !isObject(key); - - if (!data && !isSimpleGetter) { - JQLiteExpandoStore(element, 'data', data = {}); - } - - if (isSetter) { - data[key] = value; - } else { - if (keyDefined) { - if (isSimpleGetter) { - // don't create data in this case. - return data && data[key]; - } else { - extend(data, key); - } - } else { - return data; - } - } -} - -function JQLiteHasClass(element, selector) { - return ((" " + element.className + " ").replace(/[\n\t]/g, " "). - indexOf( " " + selector + " " ) > -1); -} - -function JQLiteRemoveClass(element, cssClasses) { - if (cssClasses) { - forEach(cssClasses.split(' '), function(cssClass) { - element.className = trim( - (" " + element.className + " ") - .replace(/[\n\t]/g, " ") - .replace(" " + trim(cssClass) + " ", " ") - ); - }); - } -} - -function JQLiteAddClass(element, cssClasses) { - if (cssClasses) { - forEach(cssClasses.split(' '), function(cssClass) { - if (!JQLiteHasClass(element, cssClass)) { - element.className = trim(element.className + ' ' + trim(cssClass)); - } - }); - } -} - -function JQLiteAddNodes(root, elements) { - if (elements) { - elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) - ? elements - : [ elements ]; - for(var i=0; i < elements.length; i++) { - root.push(elements[i]); - } - } -} - -function JQLiteController(element, name) { - return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); -} - -function JQLiteInheritedData(element, name, value) { - element = jqLite(element); - - // if element is the document object work with the html element instead - // this makes $(document).scope() possible - if(element[0].nodeType == 9) { - element = element.find('html'); - } - - while (element.length) { - if ((value = element.data(name)) !== undefined) return value; - element = element.parent(); - } -} - -////////////////////////////////////////// -// Functions which are declared directly. -////////////////////////////////////////// -var JQLitePrototype = JQLite.prototype = { - ready: function(fn) { - var fired = false; - - function trigger() { - if (fired) return; - fired = true; - fn(); - } - - // check if document already is loaded - if (document.readyState === 'complete'){ - setTimeout(trigger); - } else { - this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9 - // we can not use jqLite since we are not done loading and jQuery could be loaded later. - JQLite(window).on('load', trigger); // fallback to window.onload for others - } - }, - toString: function() { - var value = []; - forEach(this, function(e){ value.push('' + e);}); - return '[' + value.join(', ') + ']'; - }, - - eq: function(index) { - return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); - }, - - length: 0, - push: push, - sort: [].sort, - splice: [].splice -}; - -////////////////////////////////////////// -// Functions iterating getter/setters. -// these functions return self on setter and -// value on get. -////////////////////////////////////////// -var BOOLEAN_ATTR = {}; -forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) { - BOOLEAN_ATTR[lowercase(value)] = value; -}); -var BOOLEAN_ELEMENTS = {}; -forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { - BOOLEAN_ELEMENTS[uppercase(value)] = true; -}); - -function getBooleanAttrName(element, name) { - // check dom last since we will most likely fail on name - var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; - - // booleanAttr is here twice to minimize DOM access - return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr; -} - -forEach({ - data: JQLiteData, - inheritedData: JQLiteInheritedData, - - scope: function(element) { - return JQLiteInheritedData(element, '$scope'); - }, - - controller: JQLiteController , - - injector: function(element) { - return JQLiteInheritedData(element, '$injector'); - }, - - removeAttr: function(element,name) { - element.removeAttribute(name); - }, - - hasClass: JQLiteHasClass, - - css: function(element, name, value) { - name = camelCase(name); - - if (isDefined(value)) { - element.style[name] = value; - } else { - var val; - - if (msie <= 8) { - // this is some IE specific weirdness that jQuery 1.6.4 does not sure why - val = element.currentStyle && element.currentStyle[name]; - if (val === '') val = 'auto'; - } - - val = val || element.style[name]; - - if (msie <= 8) { - // jquery weirdness :-/ - val = (val === '') ? undefined : val; - } - - return val; - } - }, - - attr: function(element, name, value){ - var lowercasedName = lowercase(name); - if (BOOLEAN_ATTR[lowercasedName]) { - if (isDefined(value)) { - if (!!value) { - element[name] = true; - element.setAttribute(name, lowercasedName); - } else { - element[name] = false; - element.removeAttribute(lowercasedName); - } - } else { - return (element[name] || - (element.attributes.getNamedItem(name)|| noop).specified) - ? lowercasedName - : undefined; - } - } else if (isDefined(value)) { - element.setAttribute(name, value); - } else if (element.getAttribute) { - // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code - // some elements (e.g. Document) don't have get attribute, so return undefined - var ret = element.getAttribute(name, 2); - // normalize non-existing attributes to undefined (as jQuery) - return ret === null ? undefined : ret; - } - }, - - prop: function(element, name, value) { - if (isDefined(value)) { - element[name] = value; - } else { - return element[name]; - } - }, - - text: (function() { - var NODE_TYPE_TEXT_PROPERTY = []; - if (msie < 9) { - NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/ - NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/ - } else { - NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/ - NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/ - } - getText.$dv = ''; - return getText; - - function getText(element, value) { - var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType] - if (isUndefined(value)) { - return textProp ? element[textProp] : ''; - } - element[textProp] = value; - } - })(), - - val: function(element, value) { - if (isUndefined(value)) { - if (nodeName_(element) === 'SELECT' && element.multiple) { - var result = []; - forEach(element.options, function (option) { - if (option.selected) { - result.push(option.value || option.text); - } - }); - return result.length === 0 ? null : result; - } - return element.value; - } - element.value = value; - }, - - html: function(element, value) { - if (isUndefined(value)) { - return element.innerHTML; - } - for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { - JQLiteDealoc(childNodes[i]); - } - element.innerHTML = value; - } -}, function(fn, name){ - /** - * Properties: writes return selection, reads return first value - */ - JQLite.prototype[name] = function(arg1, arg2) { - var i, key; - - // JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it - // in a way that survives minification. - if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) { - if (isObject(arg1)) { - - // we are a write, but the object properties are the key/values - for(i=0; i < this.length; i++) { - if (fn === JQLiteData) { - // data() takes the whole object in jQuery - fn(this[i], arg1); - } else { - for (key in arg1) { - fn(this[i], key, arg1[key]); - } - } - } - // return self for chaining - return this; - } else { - // we are a read, so read the first child. - var value = fn.$dv; - // Only if we have $dv do we iterate over all, otherwise it is just the first element. - var jj = value == undefined ? Math.min(this.length, 1) : this.length; - for (var j = 0; j < jj; j++) { - var nodeValue = fn(this[j], arg1, arg2); - value = value ? value + nodeValue : nodeValue; - } - return value; - } - } else { - // we are a write, so apply to all children - for(i=0; i < this.length; i++) { - fn(this[i], arg1, arg2); - } - // return self for chaining - return this; - } - }; -}); - -function createEventHandler(element, events) { - var eventHandler = function (event, type) { - if (!event.preventDefault) { - event.preventDefault = function() { - event.returnValue = false; //ie - }; - } - - if (!event.stopPropagation) { - event.stopPropagation = function() { - event.cancelBubble = true; //ie - }; - } - - if (!event.target) { - event.target = event.srcElement || document; - } - - if (isUndefined(event.defaultPrevented)) { - var prevent = event.preventDefault; - event.preventDefault = function() { - event.defaultPrevented = true; - prevent.call(event); - }; - event.defaultPrevented = false; - } - - event.isDefaultPrevented = function() { - return event.defaultPrevented || event.returnValue == false; - }; - - forEach(events[type || event.type], function(fn) { - fn.call(element, event); - }); - - // Remove monkey-patched methods (IE), - // as they would cause memory leaks in IE8. - if (msie <= 8) { - // IE7/8 does not allow to delete property on native object - event.preventDefault = null; - event.stopPropagation = null; - event.isDefaultPrevented = null; - } else { - // It shouldn't affect normal browsers (native methods are defined on prototype). - delete event.preventDefault; - delete event.stopPropagation; - delete event.isDefaultPrevented; - } - }; - eventHandler.elem = element; - return eventHandler; -} - -////////////////////////////////////////// -// Functions iterating traversal. -// These functions chain results into a single -// selector. -////////////////////////////////////////// -forEach({ - removeData: JQLiteRemoveData, - - dealoc: JQLiteDealoc, - - on: function onFn(element, type, fn, unsupported){ - if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters'); - - var events = JQLiteExpandoStore(element, 'events'), - handle = JQLiteExpandoStore(element, 'handle'); - - if (!events) JQLiteExpandoStore(element, 'events', events = {}); - if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events)); - - forEach(type.split(' '), function(type){ - var eventFns = events[type]; - - if (!eventFns) { - if (type == 'mouseenter' || type == 'mouseleave') { - var contains = document.body.contains || document.body.compareDocumentPosition ? - function( a, b ) { - var adown = a.nodeType === 9 ? a.documentElement : a, - bup = b && b.parentNode; - return a === bup || !!( bup && bup.nodeType === 1 && ( - adown.contains ? - adown.contains( bup ) : - a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 - )); - } : - function( a, b ) { - if ( b ) { - while ( (b = b.parentNode) ) { - if ( b === a ) { - return true; - } - } - } - return false; - }; - - events[type] = []; - - // Refer to jQuery's implementation of mouseenter & mouseleave - // Read about mouseenter and mouseleave: - // http://www.quirksmode.org/js/events_mouse.html#link8 - var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"}; - - onFn(element, eventmap[type], function(event) { - var target = this, related = event.relatedTarget; - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !contains(target, related)) ){ - handle(event, type); - } - }); - - } else { - addEventListenerFn(element, type, handle); - events[type] = []; - } - eventFns = events[type] - } - eventFns.push(fn); - }); - }, - - off: JQLiteOff, - - replaceWith: function(element, replaceNode) { - var index, parent = element.parentNode; - JQLiteDealoc(element); - forEach(new JQLite(replaceNode), function(node){ - if (index) { - parent.insertBefore(node, index.nextSibling); - } else { - parent.replaceChild(node, element); - } - index = node; - }); - }, - - children: function(element) { - var children = []; - forEach(element.childNodes, function(element){ - if (element.nodeType === 1) - children.push(element); - }); - return children; - }, - - contents: function(element) { - return element.childNodes || []; - }, - - append: function(element, node) { - forEach(new JQLite(node), function(child){ - if (element.nodeType === 1 || element.nodeType === 11) { - element.appendChild(child); - } - }); - }, - - prepend: function(element, node) { - if (element.nodeType === 1) { - var index = element.firstChild; - forEach(new JQLite(node), function(child){ - element.insertBefore(child, index); - }); - } - }, - - wrap: function(element, wrapNode) { - wrapNode = jqLite(wrapNode)[0]; - var parent = element.parentNode; - if (parent) { - parent.replaceChild(wrapNode, element); - } - wrapNode.appendChild(element); - }, - - remove: function(element) { - JQLiteDealoc(element); - var parent = element.parentNode; - if (parent) parent.removeChild(element); - }, - - after: function(element, newElement) { - var index = element, parent = element.parentNode; - forEach(new JQLite(newElement), function(node){ - parent.insertBefore(node, index.nextSibling); - index = node; - }); - }, - - addClass: JQLiteAddClass, - removeClass: JQLiteRemoveClass, - - toggleClass: function(element, selector, condition) { - if (isUndefined(condition)) { - condition = !JQLiteHasClass(element, selector); - } - (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector); - }, - - parent: function(element) { - var parent = element.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - - next: function(element) { - if (element.nextElementSibling) { - return element.nextElementSibling; - } - - // IE8 doesn't have nextElementSibling - var elm = element.nextSibling; - while (elm != null && elm.nodeType !== 1) { - elm = elm.nextSibling; - } - return elm; - }, - - find: function(element, selector) { - return element.getElementsByTagName(selector); - }, - - clone: JQLiteClone, - - triggerHandler: function(element, eventName, eventData) { - var eventFns = (JQLiteExpandoStore(element, 'events') || {})[eventName]; - eventData = eventData || { - preventDefault: noop, - stopPropagation: noop - }; - - forEach(eventFns, function(fn) { - fn.call(element, eventData); - }); - } -}, function(fn, name){ - /** - * chaining functions - */ - JQLite.prototype[name] = function(arg1, arg2, arg3) { - var value; - for(var i=0; i < this.length; i++) { - if (value == undefined) { - value = fn(this[i], arg1, arg2, arg3); - if (value !== undefined) { - // any function which returns a value needs to be wrapped - value = jqLite(value); - } - } else { - JQLiteAddNodes(value, fn(this[i], arg1, arg2, arg3)); - } - } - return value == undefined ? this : value; - }; - - // bind legacy bind/unbind to on/off - JQLite.prototype.bind = JQLite.prototype.on; - JQLite.prototype.unbind = JQLite.prototype.off; -}); - -/** - * Computes a hash of an 'obj'. - * Hash of a: - * string is string - * number is number as string - * object is either result of calling $$hashKey function on the object or uniquely generated id, - * that is also assigned to the $$hashKey property of the object. - * - * @param obj - * @returns {string} hash string such that the same input will have the same hash string. - * The resulting string key is in 'type:hashKey' format. - */ -function hashKey(obj) { - var objType = typeof obj, - key; - - if (objType == 'object' && obj !== null) { - if (typeof (key = obj.$$hashKey) == 'function') { - // must invoke on object to keep the right this - key = obj.$$hashKey(); - } else if (key === undefined) { - key = obj.$$hashKey = nextUid(); - } - } else { - key = obj; - } - - return objType + ':' + key; -} - -/** - * HashMap which can use objects as keys - */ -function HashMap(array){ - forEach(array, this.put, this); -} -HashMap.prototype = { - /** - * Store key value pair - * @param key key to store can be any type - * @param value value to store can be any type - */ - put: function(key, value) { - this[hashKey(key)] = value; - }, - - /** - * @param key - * @returns the value for the key - */ - get: function(key) { - return this[hashKey(key)]; - }, - - /** - * Remove the key/value pair - * @param key - */ - remove: function(key) { - var value = this[key = hashKey(key)]; - delete this[key]; - return value; - } -}; - -/** - * @ngdoc function - * @name angular.injector - * @function - * - * @description - * Creates an injector function that can be used for retrieving services as well as for - * dependency injection (see {@link guide/di dependency injection}). - * - - * @param {Array.} modules A list of module functions or their aliases. See - * {@link angular.module}. The `ng` module must be explicitly added. - * @returns {function()} Injector function. See {@link AUTO.$injector $injector}. - * - * @example - * Typical usage - *
- *   // create an injector
- *   var $injector = angular.injector(['ng']);
- *
- *   // use the injector to kick off your application
- *   // use the type inference to auto inject arguments, or use implicit injection
- *   $injector.invoke(function($rootScope, $compile, $document){
- *     $compile($document)($rootScope);
- *     $rootScope.$digest();
- *   });
- * 
- */ - - -/** - * @ngdoc overview - * @name AUTO - * @description - * - * Implicit module which gets automatically added to each {@link AUTO.$injector $injector}. - */ - -var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; -var FN_ARG_SPLIT = /,/; -var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; -var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; -var $injectorMinErr = minErr('$injector'); -function annotate(fn) { - var $inject, - fnText, - argDecl, - last; - - if (typeof fn == 'function') { - if (!($inject = fn.$inject)) { - $inject = []; - fnText = fn.toString().replace(STRIP_COMMENTS, ''); - argDecl = fnText.match(FN_ARGS); - forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ - arg.replace(FN_ARG, function(all, underscore, name){ - $inject.push(name); - }); - }); - fn.$inject = $inject; - } - } else if (isArray(fn)) { - last = fn.length - 1; - assertArgFn(fn[last], 'fn'); - $inject = fn.slice(0, last); - } else { - assertArgFn(fn, 'fn', true); - } - return $inject; -} - -/////////////////////////////////////// - -/** - * @ngdoc object - * @name AUTO.$injector - * @function - * - * @description - * - * `$injector` is used to retrieve object instances as defined by - * {@link AUTO.$provide provider}, instantiate types, invoke methods, - * and load modules. - * - * The following always holds true: - * - *
- *   var $injector = angular.injector();
- *   expect($injector.get('$injector')).toBe($injector);
- *   expect($injector.invoke(function($injector){
- *     return $injector;
- *   }).toBe($injector);
- * 
- * - * # Injection Function Annotation - * - * JavaScript does not have annotations, and annotations are needed for dependency injection. The - * following are all valid ways of annotating function with injection arguments and are equivalent. - * - *
- *   // inferred (only works if code not minified/obfuscated)
- *   $injector.invoke(function(serviceA){});
- *
- *   // annotated
- *   function explicit(serviceA) {};
- *   explicit.$inject = ['serviceA'];
- *   $injector.invoke(explicit);
- *
- *   // inline
- *   $injector.invoke(['serviceA', function(serviceA){}]);
- * 
- * - * ## Inference - * - * In JavaScript calling `toString()` on a function returns the function definition. The definition can then be - * parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation - * tools since these tools change the argument names. - * - * ## `$inject` Annotation - * By adding a `$inject` property onto a function the injection parameters can be specified. - * - * ## Inline - * As an array of injection names, where the last item in the array is the function to call. - */ - -/** - * @ngdoc method - * @name AUTO.$injector#get - * @methodOf AUTO.$injector - * - * @description - * Return an instance of the service. - * - * @param {string} name The name of the instance to retrieve. - * @return {*} The instance. - */ - -/** - * @ngdoc method - * @name AUTO.$injector#invoke - * @methodOf AUTO.$injector - * - * @description - * Invoke the method and supply the method arguments from the `$injector`. - * - * @param {!function} fn The function to invoke. The function arguments come form the function annotation. - * @param {Object=} self The `this` for the invoked method. - * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before - * the `$injector` is consulted. - * @returns {*} the value returned by the invoked `fn` function. - */ - -/** - * @ngdoc method - * @name AUTO.$injector#has - * @methodOf AUTO.$injector - * - * @description - * Allows the user to query if the particular service exist. - * - * @param {string} Name of the service to query. - * @returns {boolean} returns true if injector has given service. - */ - -/** - * @ngdoc method - * @name AUTO.$injector#instantiate - * @methodOf AUTO.$injector - * @description - * Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies - * all of the arguments to the constructor function as specified by the constructor annotation. - * - * @param {function} Type Annotated constructor function. - * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before - * the `$injector` is consulted. - * @returns {Object} new instance of `Type`. - */ - -/** - * @ngdoc method - * @name AUTO.$injector#annotate - * @methodOf AUTO.$injector - * - * @description - * Returns an array of service names which the function is requesting for injection. This API is used by the injector - * to determine which services need to be injected into the function when the function is invoked. There are three - * ways in which the function can be annotated with the needed dependencies. - * - * # Argument names - * - * The simplest form is to extract the dependencies from the arguments of the function. This is done by converting - * the function into a string using `toString()` method and extracting the argument names. - *
- *   // Given
- *   function MyController($scope, $route) {
- *     // ...
- *   }
- *
- *   // Then
- *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
- * 
- * - * This method does not work with code minification / obfuscation. For this reason the following annotation strategies - * are supported. - * - * # The `$inject` property - * - * If a function has an `$inject` property and its value is an array of strings, then the strings represent names of - * services to be injected into the function. - *
- *   // Given
- *   var MyController = function(obfuscatedScope, obfuscatedRoute) {
- *     // ...
- *   }
- *   // Define function dependencies
- *   MyController.$inject = ['$scope', '$route'];
- *
- *   // Then
- *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
- * 
- * - * # The array notation - * - * It is often desirable to inline Injected functions and that's when setting the `$inject` property is very - * inconvenient. In these situations using the array notation to specify the dependencies in a way that survives - * minification is a better choice: - * - *
- *   // We wish to write this (not minification / obfuscation safe)
- *   injector.invoke(function($compile, $rootScope) {
- *     // ...
- *   });
- *
- *   // We are forced to write break inlining
- *   var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
- *     // ...
- *   };
- *   tmpFn.$inject = ['$compile', '$rootScope'];
- *   injector.invoke(tmpFn);
- *
- *   // To better support inline function the inline annotation is supported
- *   injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
- *     // ...
- *   }]);
- *
- *   // Therefore
- *   expect(injector.annotate(
- *      ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
- *    ).toEqual(['$compile', '$rootScope']);
- * 
- * - * @param {function|Array.} fn Function for which dependent service names need to be retrieved as described - * above. - * - * @returns {Array.} The names of the services which the function requires. - */ - - - - -/** - * @ngdoc object - * @name AUTO.$provide - * - * @description - * - * Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance. - * The providers share the same name as the instance they create with `Provider` suffixed to them. - * - * A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of - * a service. The Provider can have additional methods which would allow for configuration of the provider. - * - *
- *   function GreetProvider() {
- *     var salutation = 'Hello';
- *
- *     this.salutation = function(text) {
- *       salutation = text;
- *     };
- *
- *     this.$get = function() {
- *       return function (name) {
- *         return salutation + ' ' + name + '!';
- *       };
- *     };
- *   }
- *
- *   describe('Greeter', function(){
- *
- *     beforeEach(module(function($provide) {
- *       $provide.provider('greet', GreetProvider);
- *     }));
- *
- *     it('should greet', inject(function(greet) {
- *       expect(greet('angular')).toEqual('Hello angular!');
- *     }));
- *
- *     it('should allow configuration of salutation', function() {
- *       module(function(greetProvider) {
- *         greetProvider.salutation('Ahoj');
- *       });
- *       inject(function(greet) {
- *         expect(greet('angular')).toEqual('Ahoj angular!');
- *       });
- *     });
- * 
- */ - -/** - * @ngdoc method - * @name AUTO.$provide#provider - * @methodOf AUTO.$provide - * @description - * - * Register a provider for a service. The providers can be retrieved and can have additional configuration methods. - * - * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. - * @param {(Object|function())} provider If the provider is: - * - * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using - * {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created. - * - `Constructor`: a new instance of the provider will be created using - * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`. - * - * @returns {Object} registered provider instance - */ - -/** - * @ngdoc method - * @name AUTO.$provide#factory - * @methodOf AUTO.$provide - * @description - * - * A short hand for configuring services if only `$get` method is required. - * - * @param {string} name The name of the instance. - * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for - * `$provide.provider(name, {$get: $getFn})`. - * @returns {Object} registered provider instance - */ - - -/** - * @ngdoc method - * @name AUTO.$provide#service - * @methodOf AUTO.$provide - * @description - * - * A short hand for registering service of given class. - * - * @param {string} name The name of the instance. - * @param {Function} constructor A class (constructor function) that will be instantiated. - * @returns {Object} registered provider instance - */ - - -/** - * @ngdoc method - * @name AUTO.$provide#value - * @methodOf AUTO.$provide - * @description - * - * A short hand for configuring services if the `$get` method is a constant. - * - * @param {string} name The name of the instance. - * @param {*} value The value. - * @returns {Object} registered provider instance - */ - - -/** - * @ngdoc method - * @name AUTO.$provide#constant - * @methodOf AUTO.$provide - * @description - * - * A constant value, but unlike {@link AUTO.$provide#value value} it can be injected - * into configuration function (other modules) and it is not interceptable by - * {@link AUTO.$provide#decorator decorator}. - * - * @param {string} name The name of the constant. - * @param {*} value The constant value. - * @returns {Object} registered instance - */ - - -/** - * @ngdoc method - * @name AUTO.$provide#decorator - * @methodOf AUTO.$provide - * @description - * - * Decoration of service, allows the decorator to intercept the service instance creation. The - * returned instance may be the original instance, or a new instance which delegates to the - * original instance. - * - * @param {string} name The name of the service to decorate. - * @param {function()} decorator This function will be invoked when the service needs to be - * instantiated. The function is called using the {@link AUTO.$injector#invoke - * injector.invoke} method and is therefore fully injectable. Local injection arguments: - * - * * `$delegate` - The original service instance, which can be monkey patched, configured, - * decorated or delegated to. - */ - - -function createInjector(modulesToLoad) { - var INSTANTIATING = {}, - providerSuffix = 'Provider', - path = [], - loadedModules = new HashMap(), - providerCache = { - $provide: { - provider: supportObject(provider), - factory: supportObject(factory), - service: supportObject(service), - value: supportObject(value), - constant: supportObject(constant), - decorator: decorator - } - }, - providerInjector = (providerCache.$injector = - createInternalInjector(providerCache, function() { - throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); - })), - instanceCache = {}, - instanceInjector = (instanceCache.$injector = - createInternalInjector(instanceCache, function(servicename) { - var provider = providerInjector.get(servicename + providerSuffix); - return instanceInjector.invoke(provider.$get, provider); - })); - - - forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); - - return instanceInjector; - - //////////////////////////////////// - // $provider - //////////////////////////////////// - - function supportObject(delegate) { - return function(key, value) { - if (isObject(key)) { - forEach(key, reverseParams(delegate)); - } else { - return delegate(key, value); - } - } - } - - function provider(name, provider_) { - if (isFunction(provider_) || isArray(provider_)) { - provider_ = providerInjector.instantiate(provider_); - } - if (!provider_.$get) { - throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); - } - return providerCache[name + providerSuffix] = provider_; - } - - function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } - - function service(name, constructor) { - return factory(name, ['$injector', function($injector) { - return $injector.instantiate(constructor); - }]); - } - - function value(name, value) { return factory(name, valueFn(value)); } - - function constant(name, value) { - providerCache[name] = value; - instanceCache[name] = value; - } - - function decorator(serviceName, decorFn) { - var origProvider = providerInjector.get(serviceName + providerSuffix), - orig$get = origProvider.$get; - - origProvider.$get = function() { - var origInstance = instanceInjector.invoke(orig$get, origProvider); - return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); - }; - } - - //////////////////////////////////// - // Module Loading - //////////////////////////////////// - function loadModules(modulesToLoad){ - var runBlocks = []; - forEach(modulesToLoad, function(module) { - if (loadedModules.get(module)) return; - loadedModules.put(module, true); - - try { - if (isString(module)) { - var moduleFn = angularModule(module); - runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); - - for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { - var invokeArgs = invokeQueue[i], - provider = providerInjector.get(invokeArgs[0]); - - provider[invokeArgs[1]].apply(provider, invokeArgs[2]); - } - } else if (isFunction(module)) { - runBlocks.push(providerInjector.invoke(module)); - } else if (isArray(module)) { - runBlocks.push(providerInjector.invoke(module)); - } else { - assertArgFn(module, 'module'); - } - } catch (e) { - if (isArray(module)) { - module = module[module.length - 1]; - } - if (e.message && e.stack && e.stack.indexOf(e.message) == -1) { - // Safari & FF's stack traces don't contain error.message content unlike those of Chrome and IE - // So if stack doesn't contain message, we create a new string that contains both. - // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. - e = e.message + '\n' + e.stack; - } - throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", module, e.stack || e.message || e); - } - }); - return runBlocks; - } - - //////////////////////////////////// - // internal Injector - //////////////////////////////////// - - function createInternalInjector(cache, factory) { - - function getService(serviceName) { - if (cache.hasOwnProperty(serviceName)) { - if (cache[serviceName] === INSTANTIATING) { - throw $injectorMinErr('cdep', 'Circular dependency found: {0}', path.join(' <- ')); - } - return cache[serviceName]; - } else { - try { - path.unshift(serviceName); - cache[serviceName] = INSTANTIATING; - return cache[serviceName] = factory(serviceName); - } finally { - path.shift(); - } - } - } - - function invoke(fn, self, locals){ - var args = [], - $inject = annotate(fn), - length, i, - key; - - for(i = 0, length = $inject.length; i < length; i++) { - key = $inject[i]; - if (typeof key !== 'string') { - throw $injectorMinErr('itkn', 'Incorrect injection token! Expected service name as string, got {0}', key); - } - args.push( - locals && locals.hasOwnProperty(key) - ? locals[key] - : getService(key) - ); - } - if (!fn.$inject) { - // this means that we must be an array. - fn = fn[length]; - } - - - // Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke - switch (self ? -1 : args.length) { - case 0: return fn(); - case 1: return fn(args[0]); - case 2: return fn(args[0], args[1]); - case 3: return fn(args[0], args[1], args[2]); - case 4: return fn(args[0], args[1], args[2], args[3]); - case 5: return fn(args[0], args[1], args[2], args[3], args[4]); - case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); - case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); - case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]); - default: return fn.apply(self, args); - } - } - - function instantiate(Type, locals) { - var Constructor = function() {}, - instance, returnedValue; - - // Check if Type is annotated and use just the given function at n-1 as parameter - // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); - Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; - instance = new Constructor(); - returnedValue = invoke(Type, instance, locals); - - return isObject(returnedValue) ? returnedValue : instance; - } - - return { - invoke: invoke, - instantiate: instantiate, - get: getService, - annotate: annotate, - has: function(name) { - return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); - } - }; - } -} - -/** - * @ngdoc function - * @name ng.$anchorScroll - * @requires $window - * @requires $location - * @requires $rootScope - * - * @description - * When called, it checks current value of `$location.hash()` and scroll to related element, - * according to rules specified in - * {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}. - * - * It also watches the `$location.hash()` and scroll whenever it changes to match any anchor. - * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`. - */ -function $AnchorScrollProvider() { - - var autoScrollingEnabled = true; - - this.disableAutoScrolling = function() { - autoScrollingEnabled = false; - }; - - this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { - var document = $window.document; - - // helper function to get first anchor from a NodeList - // can't use filter.filter, as it accepts only instances of Array - // and IE can't convert NodeList to an array using [].slice - // TODO(vojta): use filter if we change it to accept lists as well - function getFirstAnchor(list) { - var result = null; - forEach(list, function(element) { - if (!result && lowercase(element.nodeName) === 'a') result = element; - }); - return result; - } - - function scroll() { - var hash = $location.hash(), elm; - - // empty hash, scroll to the top of the page - if (!hash) $window.scrollTo(0, 0); - - // element with given id - else if ((elm = document.getElementById(hash))) elm.scrollIntoView(); - - // first anchor with given name :-D - else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView(); - - // no element and hash == 'top', scroll to the top of the page - else if (hash === 'top') $window.scrollTo(0, 0); - } - - // does not scroll when user clicks on anchor link that is currently on - // (no url change, no $location.hash() change), browser native does scroll - if (autoScrollingEnabled) { - $rootScope.$watch(function autoScrollWatch() {return $location.hash();}, - function autoScrollWatchAction() { - $rootScope.$evalAsync(scroll); - }); - } - - return scroll; - }]; -} - -var $animateMinErr = minErr('$animate'); - -/** - * @ngdoc object - * @name ng.$animateProvider - * - * @description - * Default implementation of $animate that doesn't perform any animations, instead just synchronously performs DOM - * updates and calls done() callbacks. - * - * In order to enable animations the ngAnimate module has to be loaded. - * - * To see the functional implementation check out src/ngAnimate/animate.js - */ -var $AnimateProvider = ['$provide', function($provide) { - - this.$$selectors = {}; - - - /** - * @ngdoc function - * @name ng.$animateProvider#register - * @methodOf ng.$animateProvider - * - * @description - * Registers a new injectable animation factory function. The factory function produces the animation object which - * contains callback functions for each event that is expected to be animated. - * - * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction` must be called once the - * element animation is complete. If a function is returned then the animation service will use this function to - * cancel the animation whenever a cancel event is triggered. - * - * - *
-   *   return {
-     *     eventFn : function(element, done) {
-     *       //code to run the animation
-     *       //once complete, then run done()
-     *       return function cancellationFunction() {
-     *         //code to cancel the animation
-     *       }
-     *     }
-     *   }
-   *
- * - * @param {string} name The name of the animation. - * @param {function} factory The factory function that will be executed to return the animation object. - */ - this.register = function(name, factory) { - var key = name + '-animation'; - if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel', - "Expecting class selector starting with '.' got '{0}'.", name); - this.$$selectors[name.substr(1)] = key; - $provide.factory(key, factory); - }; - - this.$get = ['$timeout', function($timeout) { - - /** - * @ngdoc object - * @name ng.$animate - * - * @description - * The $animate service provides rudimentary DOM manipulation functions to insert, remove, move elements within - * the DOM as well as adding and removing classes. This service is the core service used by the ngAnimate $animator - * service which provides high-level animation hooks for CSS and JavaScript. - * - * $animate is available in the AngularJS core, however, the ngAnimate module must be included to enable full out - * animation support. Otherwise, $animate will only perform simple DOM manipulation operations. - * - * To learn more about enabling animation support, click here to visit the {@link ngAnimate ngAnimate module page} - * as well as the {@link ngAnimate.$animate ngAnimate $animate service page}. - */ - return { - - /** - * @ngdoc function - * @name ng.$animate#enter - * @methodOf ng.$animate - * @function - * - * @description - * Inserts the element into the DOM either after the `after` element or within the `parent` element. Once complete, - * the done() callback will be fired (if provided). - * - * @param {jQuery/jqLite element} element the element which will be inserted into the DOM - * @param {jQuery/jqLite element} parent the parent element which will append the element as a child (if the after element is not present) - * @param {jQuery/jqLite element} after the sibling element which will append the element after itself - * @param {function=} done callback function that will be called after the element has been inserted into the DOM - */ - enter : function(element, parent, after, done) { - var afterNode = after && after[after.length - 1]; - var parentNode = parent && parent[0] || afterNode && afterNode.parentNode; - // IE does not like undefined so we have to pass null. - var afterNextSibling = (afterNode && afterNode.nextSibling) || null; - forEach(element, function(node) { - parentNode.insertBefore(node, afterNextSibling); - }); - $timeout(done || noop, 0, false); - }, - - /** - * @ngdoc function - * @name ng.$animate#leave - * @methodOf ng.$animate - * @function - * - * @description - * Removes the element from the DOM. Once complete, the done() callback will be fired (if provided). - * - * @param {jQuery/jqLite element} element the element which will be removed from the DOM - * @param {function=} done callback function that will be called after the element has been removed from the DOM - */ - leave : function(element, done) { - element.remove(); - $timeout(done || noop, 0, false); - }, - - /** - * @ngdoc function - * @name ng.$animate#move - * @methodOf ng.$animate - * @function - * - * @description - * Moves the position of the provided element within the DOM to be placed either after the `after` element or inside of the `parent` element. - * Once complete, the done() callback will be fired (if provided). - * - * @param {jQuery/jqLite element} element the element which will be moved around within the DOM - * @param {jQuery/jqLite element} parent the parent element where the element will be inserted into (if the after element is not present) - * @param {jQuery/jqLite element} after the sibling element where the element will be positioned next to - * @param {function=} done the callback function (if provided) that will be fired after the element has been moved to it's new position - */ - move : function(element, parent, after, done) { - // Do not remove element before insert. Removing will cause data associated with the - // element to be dropped. Insert will implicitly do the remove. - this.enter(element, parent, after, done); - }, - - /** - * @ngdoc function - * @name ng.$animate#addClass - * @methodOf ng.$animate - * @function - * - * @description - * Adds the provided className CSS class value to the provided element. Once complete, the done() callback will be fired (if provided). - * - * @param {jQuery/jqLite element} element the element which will have the className value added to it - * @param {string} className the CSS class which will be added to the element - * @param {function=} done the callback function (if provided) that will be fired after the className value has been added to the element - */ - addClass : function(element, className, done) { - className = isString(className) ? - className : - isArray(className) ? className.join(' ') : ''; - element.addClass(className); - $timeout(done || noop, 0, false); - }, - - /** - * @ngdoc function - * @name ng.$animate#removeClass - * @methodOf ng.$animate - * @function - * - * @description - * Removes the provided className CSS class value from the provided element. Once complete, the done() callback will be fired (if provided). - * - * @param {jQuery/jqLite element} element the element which will have the className value removed from it - * @param {string} className the CSS class which will be removed from the element - * @param {function=} done the callback function (if provided) that will be fired after the className value has been removed from the element - */ - removeClass : function(element, className, done) { - className = isString(className) ? - className : - isArray(className) ? className.join(' ') : ''; - element.removeClass(className); - $timeout(done || noop, 0, false); - }, - - enabled : noop - }; - }]; -}]; - -/** - * ! This is a private undocumented service ! - * - * @name ng.$browser - * @requires $log - * @description - * This object has two goals: - * - * - hide all the global state in the browser caused by the window object - * - abstract away all the browser specific features and inconsistencies - * - * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` - * service, which can be used for convenient testing of the application without the interaction with - * the real browser apis. - */ -/** - * @param {object} window The global window object. - * @param {object} document jQuery wrapped document. - * @param {function()} XHR XMLHttpRequest constructor. - * @param {object} $log console.log or an object with the same interface. - * @param {object} $sniffer $sniffer service - */ -function Browser(window, document, $log, $sniffer) { - var self = this, - rawDocument = document[0], - location = window.location, - history = window.history, - setTimeout = window.setTimeout, - clearTimeout = window.clearTimeout, - pendingDeferIds = {}; - - self.isMock = false; - - var outstandingRequestCount = 0; - var outstandingRequestCallbacks = []; - - // TODO(vojta): remove this temporary api - self.$$completeOutstandingRequest = completeOutstandingRequest; - self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; - - /** - * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` - * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. - */ - function completeOutstandingRequest(fn) { - try { - fn.apply(null, sliceArgs(arguments, 1)); - } finally { - outstandingRequestCount--; - if (outstandingRequestCount === 0) { - while(outstandingRequestCallbacks.length) { - try { - outstandingRequestCallbacks.pop()(); - } catch (e) { - $log.error(e); - } - } - } - } - } - - /** - * @private - * Note: this method is used only by scenario runner - * TODO(vojta): prefix this method with $$ ? - * @param {function()} callback Function that will be called when no outstanding request - */ - self.notifyWhenNoOutstandingRequests = function(callback) { - // force browser to execute all pollFns - this is needed so that cookies and other pollers fire - // at some deterministic time in respect to the test runner's actions. Leaving things up to the - // regular poller would result in flaky tests. - forEach(pollFns, function(pollFn){ pollFn(); }); - - if (outstandingRequestCount === 0) { - callback(); - } else { - outstandingRequestCallbacks.push(callback); - } - }; - - ////////////////////////////////////////////////////////////// - // Poll Watcher API - ////////////////////////////////////////////////////////////// - var pollFns = [], - pollTimeout; - - /** - * @name ng.$browser#addPollFn - * @methodOf ng.$browser - * - * @param {function()} fn Poll function to add - * - * @description - * Adds a function to the list of functions that poller periodically executes, - * and starts polling if not started yet. - * - * @returns {function()} the added function - */ - self.addPollFn = function(fn) { - if (isUndefined(pollTimeout)) startPoller(100, setTimeout); - pollFns.push(fn); - return fn; - }; - - /** - * @param {number} interval How often should browser call poll functions (ms) - * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. - * - * @description - * Configures the poller to run in the specified intervals, using the specified - * setTimeout fn and kicks it off. - */ - function startPoller(interval, setTimeout) { - (function check() { - forEach(pollFns, function(pollFn){ pollFn(); }); - pollTimeout = setTimeout(check, interval); - })(); - } - - ////////////////////////////////////////////////////////////// - // URL API - ////////////////////////////////////////////////////////////// - - var lastBrowserUrl = location.href, - baseElement = document.find('base'), - replacedUrl = null; - - /** - * @name ng.$browser#url - * @methodOf ng.$browser - * - * @description - * GETTER: - * Without any argument, this method just returns current value of location.href. - * - * SETTER: - * With at least one argument, this method sets url to new value. - * If html5 history api supported, pushState/replaceState is used, otherwise - * location.href/location.replace is used. - * Returns its own instance to allow chaining - * - * NOTE: this api is intended for use only by the $location service. Please use the - * {@link ng.$location $location service} to change url. - * - * @param {string} url New url (when used as setter) - * @param {boolean=} replace Should new url replace current history record ? - */ - self.url = function(url, replace) { - // setter - if (url) { - if (lastBrowserUrl == url) return; - lastBrowserUrl = url; - if ($sniffer.history) { - if (replace) history.replaceState(null, '', url); - else { - history.pushState(null, '', url); - // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462 - baseElement.attr('href', baseElement.attr('href')); - } - } else { - if (replace) { - location.replace(url); - replacedUrl = url; - } else { - location.href = url; - replacedUrl = null; - } - } - return self; - // getter - } else { - // - the replacedUrl is a workaround for an IE8-9 issue with location.replace method that doesn't update - // location.href synchronously - // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 - return replacedUrl || location.href.replace(/%27/g,"'"); - } - }; - - var urlChangeListeners = [], - urlChangeInit = false; - - function fireUrlChange() { - if (lastBrowserUrl == self.url()) return; - - lastBrowserUrl = self.url(); - forEach(urlChangeListeners, function(listener) { - listener(self.url()); - }); - } - - /** - * @name ng.$browser#onUrlChange - * @methodOf ng.$browser - * @TODO(vojta): refactor to use node's syntax for events - * - * @description - * Register callback function that will be called, when url changes. - * - * It's only called when the url is changed by outside of angular: - * - user types different url into address bar - * - user clicks on history (forward/back) button - * - user clicks on a link - * - * It's not called when url is changed by $browser.url() method - * - * The listener gets called with new url as parameter. - * - * NOTE: this api is intended for use only by the $location service. Please use the - * {@link ng.$location $location service} to monitor url changes in angular apps. - * - * @param {function(string)} listener Listener function to be called when url changes. - * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. - */ - self.onUrlChange = function(callback) { - if (!urlChangeInit) { - // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) - // don't fire popstate when user change the address bar and don't fire hashchange when url - // changed by push/replaceState - - // html5 history api - popstate event - if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange); - // hashchange event - if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange); - // polling - else self.addPollFn(fireUrlChange); - - urlChangeInit = true; - } - - urlChangeListeners.push(callback); - return callback; - }; - - ////////////////////////////////////////////////////////////// - // Misc API - ////////////////////////////////////////////////////////////// - - /** - * Returns current - * (always relative - without domain) - * - * @returns {string=} - */ - self.baseHref = function() { - var href = baseElement.attr('href'); - return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : ''; - }; - - ////////////////////////////////////////////////////////////// - // Cookies API - ////////////////////////////////////////////////////////////// - var lastCookies = {}; - var lastCookieString = ''; - var cookiePath = self.baseHref(); - - /** - * @name ng.$browser#cookies - * @methodOf ng.$browser - * - * @param {string=} name Cookie name - * @param {string=} value Cookie value - * - * @description - * The cookies method provides a 'private' low level access to browser cookies. - * It is not meant to be used directly, use the $cookie service instead. - * - * The return values vary depending on the arguments that the method was called with as follows: - *
    - *
  • cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it
  • - *
  • cookies(name, value) -> set name to value, if value is undefined delete the cookie
  • - *
  • cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)
  • - *
- * - * @returns {Object} Hash of all cookies (if called without any parameter) - */ - self.cookies = function(name, value) { - var cookieLength, cookieArray, cookie, i, index; - - if (name) { - if (value === undefined) { - rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; - } else { - if (isString(value)) { - cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1; - - // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: - // - 300 cookies - // - 20 cookies per unique domain - // - 4096 bytes per cookie - if (cookieLength > 4096) { - $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+ - cookieLength + " > 4096 bytes)!"); - } - } - } - } else { - if (rawDocument.cookie !== lastCookieString) { - lastCookieString = rawDocument.cookie; - cookieArray = lastCookieString.split("; "); - lastCookies = {}; - - for (i = 0; i < cookieArray.length; i++) { - cookie = cookieArray[i]; - index = cookie.indexOf('='); - if (index > 0) { //ignore nameless cookies - var name = unescape(cookie.substring(0, index)); - // the first value that is seen for a cookie is the most - // specific one. values for the same cookie name that - // follow are for less specific paths. - if (lastCookies[name] === undefined) { - lastCookies[name] = unescape(cookie.substring(index + 1)); - } - } - } - } - return lastCookies; - } - }; - - - /** - * @name ng.$browser#defer - * @methodOf ng.$browser - * @param {function()} fn A function, who's execution should be deferred. - * @param {number=} [delay=0] of milliseconds to defer the function execution. - * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. - * - * @description - * Executes a fn asynchronously via `setTimeout(fn, delay)`. - * - * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using - * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed - * via `$browser.defer.flush()`. - * - */ - self.defer = function(fn, delay) { - var timeoutId; - outstandingRequestCount++; - timeoutId = setTimeout(function() { - delete pendingDeferIds[timeoutId]; - completeOutstandingRequest(fn); - }, delay || 0); - pendingDeferIds[timeoutId] = true; - return timeoutId; - }; - - - /** - * @name ng.$browser#defer.cancel - * @methodOf ng.$browser.defer - * - * @description - * Cancels a deferred task identified with `deferId`. - * - * @param {*} deferId Token returned by the `$browser.defer` function. - * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully canceled. - */ - self.defer.cancel = function(deferId) { - if (pendingDeferIds[deferId]) { - delete pendingDeferIds[deferId]; - clearTimeout(deferId); - completeOutstandingRequest(noop); - return true; - } - return false; - }; - -} - -function $BrowserProvider(){ - this.$get = ['$window', '$log', '$sniffer', '$document', - function( $window, $log, $sniffer, $document){ - return new Browser($window, $document, $log, $sniffer); - }]; -} - -/** - * @ngdoc object - * @name ng.$cacheFactory - * - * @description - * Factory that constructs cache objects and gives access to them. - * - *
- * 
- *  var cache = $cacheFactory('cacheId');
- *  expect($cacheFactory.get('cacheId')).toBe(cache);
- *  expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
- *
- *  cache.put("key", "value");
- *  cache.put("another key", "another value");
- * 
- *  expect(cache.info()).toEqual({id: 'cacheId', size: 2}); // Since we've specified no options on creation
- * 
- * 
- * - * - * @param {string} cacheId Name or id of the newly created cache. - * @param {object=} options Options object that specifies the cache behavior. Properties: - * - * - `{number=}` `capacity` — turns the cache into LRU cache. - * - * @returns {object} Newly created cache object with the following set of methods: - * - * - `{object}` `info()` — Returns id, size, and options of cache. - * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns it. - * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss. - * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache. - * - `{void}` `removeAll()` — Removes all cached values. - * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. - * - */ -function $CacheFactoryProvider() { - - this.$get = function() { - var caches = {}; - - function cacheFactory(cacheId, options) { - if (cacheId in caches) { - throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId); - } - - var size = 0, - stats = extend({}, options, {id: cacheId}), - data = {}, - capacity = (options && options.capacity) || Number.MAX_VALUE, - lruHash = {}, - freshEnd = null, - staleEnd = null; - - return caches[cacheId] = { - - put: function(key, value) { - var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); - - refresh(lruEntry); - - if (isUndefined(value)) return; - if (!(key in data)) size++; - data[key] = value; - - if (size > capacity) { - this.remove(staleEnd.key); - } - - return value; - }, - - - get: function(key) { - var lruEntry = lruHash[key]; - - if (!lruEntry) return; - - refresh(lruEntry); - - return data[key]; - }, - - - remove: function(key) { - var lruEntry = lruHash[key]; - - if (!lruEntry) return; - - if (lruEntry == freshEnd) freshEnd = lruEntry.p; - if (lruEntry == staleEnd) staleEnd = lruEntry.n; - link(lruEntry.n,lruEntry.p); - - delete lruHash[key]; - delete data[key]; - size--; - }, - - - removeAll: function() { - data = {}; - size = 0; - lruHash = {}; - freshEnd = staleEnd = null; - }, - - - destroy: function() { - data = null; - stats = null; - lruHash = null; - delete caches[cacheId]; - }, - - - info: function() { - return extend({}, stats, {size: size}); - } - }; - - - /** - * makes the `entry` the freshEnd of the LRU linked list - */ - function refresh(entry) { - if (entry != freshEnd) { - if (!staleEnd) { - staleEnd = entry; - } else if (staleEnd == entry) { - staleEnd = entry.n; - } - - link(entry.n, entry.p); - link(entry, freshEnd); - freshEnd = entry; - freshEnd.n = null; - } - } - - - /** - * bidirectionally links two entries of the LRU linked list - */ - function link(nextEntry, prevEntry) { - if (nextEntry != prevEntry) { - if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify - if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify - } - } - } - - - /** - * @ngdoc method - * @name ng.$cacheFactory#info - * @methodOf ng.$cacheFactory - * - * @description - * Get information about all the of the caches that have been created - * - * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info` - */ - cacheFactory.info = function() { - var info = {}; - forEach(caches, function(cache, cacheId) { - info[cacheId] = cache.info(); - }); - return info; - }; - - - /** - * @ngdoc method - * @name ng.$cacheFactory#get - * @methodOf ng.$cacheFactory - * - * @description - * Get access to a cache object by the `cacheId` used when it was created. - * - * @param {string} cacheId Name or id of a cache to access. - * @returns {object} Cache object identified by the cacheId or undefined if no such cache. - */ - cacheFactory.get = function(cacheId) { - return caches[cacheId]; - }; - - - return cacheFactory; - }; -} - -/** - * @ngdoc object - * @name ng.$templateCache - * - * @description - * The first time a template is used, it is loaded in the template cache for quick retrieval. You can - * load templates directly into the cache in a `script` tag, or by consuming the `$templateCache` - * service directly. - * - * Adding via the `script` tag: - *
- * 
- * 
- * 
- * 
- *   ...
- * 
- * 
- * - * **Note:** the `script` tag containing the template does not need to be included in the `head` of the document, but - * it must be below the `ng-app` definition. - * - * Adding via the $templateCache service: - * - *
- * var myApp = angular.module('myApp', []);
- * myApp.run(function($templateCache) {
- *   $templateCache.put('templateId.html', 'This is the content of the template');
- * });
- * 
- * - * To retrieve the template later, simply use it in your HTML: - *
- * 
- *
- * - * or get it via Javascript: - *
- * $templateCache.get('templateId.html')
- * 
- * - * See {@link ng.$cacheFactory $cacheFactory}. - * - */ -function $TemplateCacheProvider() { - this.$get = ['$cacheFactory', function($cacheFactory) { - return $cacheFactory('templates'); - }]; -} - -/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! - * - * DOM-related variables: - * - * - "node" - DOM Node - * - "element" - DOM Element or Node - * - "$node" or "$element" - jqLite-wrapped node or element - * - * - * Compiler related stuff: - * - * - "linkFn" - linking fn of a single directive - * - "nodeLinkFn" - function that aggregates all linking fns for a particular node - * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node - * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) - */ - - -/** - * @ngdoc function - * @name ng.$compile - * @function - * - * @description - * Compiles a piece of HTML string or DOM into a template and produces a template function, which - * can then be used to link {@link ng.$rootScope.Scope scope} and the template together. - * - * The compilation is a process of walking the DOM tree and trying to match DOM elements to - * {@link ng.$compileProvider#directive directives}. For each match it - * executes corresponding template function and collects the - * instance functions into a single template function which is then returned. - * - * The template function can then be used once to produce the view or as it is the case with - * {@link ng.directive:ngRepeat repeater} many-times, in which - * case each call results in a view that is a DOM clone of the original template. - * - - - -
-
-
-
-
-
- - it('should auto compile', function() { - expect(element('div[compile]').text()).toBe('Hello Angular'); - input('html').enter('{{name}}!'); - expect(element('div[compile]').text()).toBe('Angular!'); - }); - -
- - * - * - * @param {string|DOMElement} element Element or HTML string to compile into a template function. - * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives. - * @param {number} maxPriority only apply directives lower then given priority (Only effects the - * root element(s), not their children) - * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template - * (a DOM element/tree) to a scope. Where: - * - * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. - * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the - * `template` and call the `cloneAttachFn` function allowing the caller to attach the - * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is - * called as:
`cloneAttachFn(clonedElement, scope)` where: - * - * * `clonedElement` - is a clone of the original `element` passed into the compiler. - * * `scope` - is the current scope with which the linking function is working with. - * - * Calling the linking function returns the element of the template. It is either the original element - * passed in, or the clone of the element if the `cloneAttachFn` is provided. - * - * After linking the view is not updated until after a call to $digest which typically is done by - * Angular automatically. - * - * If you need access to the bound view, there are two ways to do it: - * - * - If you are not asking the linking function to clone the template, create the DOM element(s) - * before you send them to the compiler and keep this reference around. - *
- *     var element = $compile('

{{total}}

')(scope); - *
- * - * - if on the other hand, you need the element to be cloned, the view reference from the original - * example would not point to the clone, but rather to the original template that was cloned. In - * this case, you can access the clone via the cloneAttachFn: - *
- *     var templateHTML = angular.element('

{{total}}

'), - * scope = ....; - * - * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) { - * //attach the clone to DOM document at the right place - * }); - * - * //now we have reference to the cloned DOM via `clone` - *
- * - * - * For information on how the compiler works, see the - * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. - */ - -var $compileMinErr = minErr('$compile'); - -/** - * @ngdoc service - * @name ng.$compileProvider - * @function - * - * @description - */ -$CompileProvider.$inject = ['$provide']; -function $CompileProvider($provide) { - var hasDirectives = {}, - Suffix = 'Directive', - COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, - CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/, - aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|file):/, - imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//; - - // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes - // The assumption is that future DOM event attribute names will begin with - // 'on' and be composed of only English letters. - var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]*|formaction)$/; - - /** - * @ngdoc function - * @name ng.$compileProvider#directive - * @methodOf ng.$compileProvider - * @function - * - * @description - * Register a new directive with the compiler. - * - * @param {string} name Name of the directive in camel-case. (ie ngBind which will match as - * ng-bind). - * @param {function|Array} directiveFactory An injectable directive factory function. See {@link guide/directive} for more - * info. - * @returns {ng.$compileProvider} Self for chaining. - */ - this.directive = function registerDirective(name, directiveFactory) { - if (isString(name)) { - assertArg(directiveFactory, 'directiveFactory'); - if (!hasDirectives.hasOwnProperty(name)) { - hasDirectives[name] = []; - $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', - function($injector, $exceptionHandler) { - var directives = []; - forEach(hasDirectives[name], function(directiveFactory) { - try { - var directive = $injector.invoke(directiveFactory); - if (isFunction(directive)) { - directive = { compile: valueFn(directive) }; - } else if (!directive.compile && directive.link) { - directive.compile = valueFn(directive.link); - } - directive.priority = directive.priority || 0; - directive.name = directive.name || name; - directive.require = directive.require || (directive.controller && directive.name); - directive.restrict = directive.restrict || 'A'; - directives.push(directive); - } catch (e) { - $exceptionHandler(e); - } - }); - return directives; - }]); - } - hasDirectives[name].push(directiveFactory); - } else { - forEach(name, reverseParams(registerDirective)); - } - return this; - }; - - - /** - * @ngdoc function - * @name ng.$compileProvider#aHrefSanitizationWhitelist - * @methodOf ng.$compileProvider - * @function - * - * @description - * Retrieves or overrides the default regular expression that is used for whitelisting of safe - * urls during a[href] sanitization. - * - * The sanitization is a security measure aimed at prevent XSS attacks via html links. - * - * Any url about to be assigned to a[href] via data-binding is first normalized and turned into - * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` - * regular expression. If a match is found, the original url is written into the dom. Otherwise, - * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. - * - * @param {RegExp=} regexp New regexp to whitelist urls with. - * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for - * chaining otherwise. - */ - this.aHrefSanitizationWhitelist = function(regexp) { - if (isDefined(regexp)) { - aHrefSanitizationWhitelist = regexp; - return this; - } - return aHrefSanitizationWhitelist; - }; - - - /** - * @ngdoc function - * @name ng.$compileProvider#imgSrcSanitizationWhitelist - * @methodOf ng.$compileProvider - * @function - * - * @description - * Retrieves or overrides the default regular expression that is used for whitelisting of safe - * urls during img[src] sanitization. - * - * The sanitization is a security measure aimed at prevent XSS attacks via html links. - * - * Any url about to be assigned to img[src] via data-binding is first normalized and turned into an - * absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` regular - * expression. If a match is found, the original url is written into the dom. Otherwise, the - * absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. - * - * @param {RegExp=} regexp New regexp to whitelist urls with. - * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for - * chaining otherwise. - */ - this.imgSrcSanitizationWhitelist = function(regexp) { - if (isDefined(regexp)) { - imgSrcSanitizationWhitelist = regexp; - return this; - } - return imgSrcSanitizationWhitelist; - }; - - - this.$get = [ - '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', - '$controller', '$rootScope', '$document', '$sce', '$$urlUtils', '$animate', - function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, - $controller, $rootScope, $document, $sce, $$urlUtils, $animate) { - - var Attributes = function(element, attr) { - this.$$element = element; - this.$attr = attr || {}; - }; - - Attributes.prototype = { - $normalize: directiveNormalize, - - - /** - * @ngdoc function - * @name ng.$compile.directive.Attributes#$addClass - * @methodOf ng.$compile.directive.Attributes - * @function - * - * @description - * Adds the CSS class value specified by the classVal parameter to the element. If animations - * are enabled then an animation will be triggered for the class addition. - * - * @param {string} classVal The className value that will be added to the element - */ - $addClass : function(classVal) { - if(classVal && classVal.length > 0) { - $animate.addClass(this.$$element, classVal); - } - }, - - /** - * @ngdoc function - * @name ng.$compile.directive.Attributes#$removeClass - * @methodOf ng.$compile.directive.Attributes - * @function - * - * @description - * Removes the CSS class value specified by the classVal parameter from the element. If animations - * are enabled then an animation will be triggered for the class removal. - * - * @param {string} classVal The className value that will be removed from the element - */ - $removeClass : function(classVal) { - if(classVal && classVal.length > 0) { - $animate.removeClass(this.$$element, classVal); - } - }, - - /** - * Set a normalized attribute on the element in a way such that all directives - * can share the attribute. This function properly handles boolean attributes. - * @param {string} key Normalized key. (ie ngAttribute) - * @param {string|boolean} value The value to set. If `null` attribute will be deleted. - * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. - * Defaults to true. - * @param {string=} attrName Optional none normalized name. Defaults to key. - */ - $set: function(key, value, writeAttr, attrName) { - //special case for class attribute addition + removal - //so that class changes can tap into the animation - //hooks provided by the $animate service - if(key == 'class') { - value = value || ''; - var current = this.$$element.attr('class') || ''; - this.$removeClass(tokenDifference(current, value).join(' ')); - this.$addClass(tokenDifference(value, current).join(' ')); - } else { - var booleanKey = getBooleanAttrName(this.$$element[0], key), - normalizedVal, - nodeName; - - if (booleanKey) { - this.$$element.prop(key, value); - attrName = booleanKey; - } - - this[key] = value; - - // translate normalized key to actual key - if (attrName) { - this.$attr[key] = attrName; - } else { - attrName = this.$attr[key]; - if (!attrName) { - this.$attr[key] = attrName = snake_case(key, '-'); - } - } - - nodeName = nodeName_(this.$$element); - - // sanitize a[href] and img[src] values - if ((nodeName === 'A' && key === 'href') || - (nodeName === 'IMG' && key === 'src')) { - // NOTE: $$urlUtils.resolve() doesn't support IE < 8 so we don't sanitize for that case. - if (!msie || msie >= 8 ) { - normalizedVal = $$urlUtils.resolve(value); - if (normalizedVal !== '') { - if ((key === 'href' && !normalizedVal.match(aHrefSanitizationWhitelist)) || - (key === 'src' && !normalizedVal.match(imgSrcSanitizationWhitelist))) { - this[key] = value = 'unsafe:' + normalizedVal; - } - } - } - } - - if (writeAttr !== false) { - if (value === null || value === undefined) { - this.$$element.removeAttr(attrName); - } else { - this.$$element.attr(attrName, value); - } - } - } - - // fire observers - var $$observers = this.$$observers; - $$observers && forEach($$observers[key], function(fn) { - try { - fn(value); - } catch (e) { - $exceptionHandler(e); - } - }); - - function tokenDifference(str1, str2) { - var values = [], - tokens1 = str1.split(/\s+/), - tokens2 = str2.split(/\s+/); - - outer: - for(var i=0;i - forEach($compileNodes, function(node, index){ - if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) { - $compileNodes[index] = node = jqLite(node).wrap('').parent()[0]; - } - }); - var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority, ignoreDirective); - return function publicLinkFn(scope, cloneConnectFn){ - assertArg(scope, 'scope'); - // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart - // and sometimes changes the structure of the DOM. - var $linkNode = cloneConnectFn - ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!! - : $compileNodes; - - // Attach scope only to non-text nodes. - for(var i = 0, ii = $linkNode.length; i - addDirective(directives, - directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective); - - // iterate over the attributes - for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes, - j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { - var attrStartName; - var attrEndName; - var index; - - attr = nAttrs[j]; - if (!msie || msie >= 8 || attr.specified) { - name = attr.name; - // support ngAttr attribute binding - ngAttrName = directiveNormalize(name); - if (NG_ATTR_BINDING.test(ngAttrName)) { - name = ngAttrName.substr(6).toLowerCase(); - } - if ((index = ngAttrName.lastIndexOf('Start')) != -1 && index == ngAttrName.length - 5) { - attrStartName = name; - attrEndName = name.substr(0, name.length - 5) + 'end'; - name = name.substr(0, name.length - 6); - } - nName = directiveNormalize(name.toLowerCase()); - attrsMap[nName] = name; - attrs[nName] = value = trim((msie && name == 'href') - ? decodeURIComponent(node.getAttribute(name, 2)) - : attr.value); - if (getBooleanAttrName(node, nName)) { - attrs[nName] = true; // presence means true - } - addAttrInterpolateDirective(node, directives, value, nName); - addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, attrEndName); - } - } - - // use class as directive - className = node.className; - if (isString(className) && className !== '') { - while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { - nName = directiveNormalize(match[2]); - if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) { - attrs[nName] = trim(match[3]); - } - className = className.substr(match.index + match[0].length); - } - } - break; - case 3: /* Text Node */ - addTextInterpolateDirective(directives, node.nodeValue); - break; - case 8: /* Comment */ - try { - match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); - if (match) { - nName = directiveNormalize(match[1]); - if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { - attrs[nName] = trim(match[2]); - } - } - } catch (e) { - // turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value. - // Just ignore it and continue. (Can't seem to reproduce in test case.) - } - break; - } - - directives.sort(byPriority); - return directives; - } - - /** - * Given a node with an directive-start it collects all of the siblings until it find directive-end. - * @param node - * @param attrStart - * @param attrEnd - * @returns {*} - */ - function groupScan(node, attrStart, attrEnd) { - var nodes = []; - var depth = 0; - if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { - var startNode = node; - do { - if (!node) { - throw $compileMinErr('uterdir', "Unterminated attribute, found '{0}' but no matching '{1}' found.", attrStart, attrEnd); - } - if (node.nodeType == 1 /** Element **/) { - if (node.hasAttribute(attrStart)) depth++; - if (node.hasAttribute(attrEnd)) depth--; - } - nodes.push(node); - node = node.nextSibling; - } while (depth > 0); - } else { - nodes.push(node); - } - return jqLite(nodes); - } - - /** - * Wrapper for linking function which converts normal linking function into a grouped - * linking function. - * @param linkFn - * @param attrStart - * @param attrEnd - * @returns {Function} - */ - function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) { - return function(scope, element, attrs, controllers) { - element = groupScan(element[0], attrStart, attrEnd); - return linkFn(scope, element, attrs, controllers); - } - } - - /** - * Once the directives have been collected, their compile functions are executed. This method - * is responsible for inlining directive templates as well as terminating the application - * of the directives if the terminal directive has been reached. - * - * @param {Array} directives Array of collected directives to execute their compile function. - * this needs to be pre-sorted by priority order. - * @param {Node} compileNode The raw DOM node to apply the compile functions to - * @param {Object} templateAttrs The shared attribute function - * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the - * scope argument is auto-generated to the new child of the transcluded parent scope. - * @param {JQLite} jqCollection If we are working on the root of the compile tree then this - * argument has the root jqLite array so that we can replace nodes on it. - * @returns linkFn - */ - function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection, originalReplaceDirective) { - var terminalPriority = -Number.MAX_VALUE, - preLinkFns = [], - postLinkFns = [], - newScopeDirective = null, - newIsolateScopeDirective = null, - templateDirective = null, - $compileNode = templateAttrs.$$element = jqLite(compileNode), - directive, - directiveName, - $template, - transcludeDirective, - replaceDirective = originalReplaceDirective, - childTranscludeFn = transcludeFn, - controllerDirectives, - linkFn, - directiveValue; - - // executes all directives on the current element - for(var i = 0, ii = directives.length; i < ii; i++) { - directive = directives[i]; - var attrStart = directive.$$start; - var attrEnd = directive.$$end; - - // collect multiblock sections - if (attrStart) { - $compileNode = groupScan(compileNode, attrStart, attrEnd) - } - $template = undefined; - - if (terminalPriority > directive.priority) { - break; // prevent further processing of directives - } - - if (directiveValue = directive.scope) { - assertNoDuplicate('isolated scope', newIsolateScopeDirective, directive, $compileNode); - if (isObject(directiveValue)) { - safeAddClass($compileNode, 'ng-isolate-scope'); - newIsolateScopeDirective = directive; - } - safeAddClass($compileNode, 'ng-scope'); - newScopeDirective = newScopeDirective || directive; - } - - directiveName = directive.name; - - if (directiveValue = directive.controller) { - controllerDirectives = controllerDirectives || {}; - assertNoDuplicate("'" + directiveName + "' controller", - controllerDirectives[directiveName], directive, $compileNode); - controllerDirectives[directiveName] = directive; - } - - if (directiveValue = directive.transclude) { - assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode); - transcludeDirective = directive; - terminalPriority = directive.priority; - if (directiveValue == 'element') { - $template = groupScan(compileNode, attrStart, attrEnd) - $compileNode = templateAttrs.$$element = - jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' ')); - compileNode = $compileNode[0]; - replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode); - - childTranscludeFn = compile($template, transcludeFn, terminalPriority, - replaceDirective && replaceDirective.name); - } else { - $template = jqLite(JQLiteClone(compileNode)).contents(); - $compileNode.html(''); // clear contents - childTranscludeFn = compile($template, transcludeFn); - } - } - - if (directive.template) { - assertNoDuplicate('template', templateDirective, directive, $compileNode); - templateDirective = directive; - - directiveValue = (isFunction(directive.template)) - ? directive.template($compileNode, templateAttrs) - : directive.template; - - directiveValue = denormalizeTemplate(directiveValue); - - if (directive.replace) { - replaceDirective = directive; - $template = jqLite('
' + - trim(directiveValue) + - '
').contents(); - compileNode = $template[0]; - - if ($template.length != 1 || compileNode.nodeType !== 1) { - throw $compileMinErr('tplrt', "Template for directive '{0}' must have exactly one root element. {1}", directiveName, ''); - } - - replaceWith(jqCollection, $compileNode, compileNode); - - var newTemplateAttrs = {$attr: {}}; - - // combine directives from the original node and from the template: - // - take the array of directives for this element - // - split it into two parts, those that were already applied and those that weren't - // - collect directives from the template, add them to the second group and sort them - // - append the second group with new directives to the first group - directives = directives.concat( - collectDirectives( - compileNode, - directives.splice(i + 1, directives.length - (i + 1)), - newTemplateAttrs - ) - ); - mergeTemplateAttributes(templateAttrs, newTemplateAttrs); - - ii = directives.length; - } else { - $compileNode.html(directiveValue); - } - } - - if (directive.templateUrl) { - assertNoDuplicate('template', templateDirective, directive, $compileNode); - templateDirective = directive; - - if (directive.replace) { - replaceDirective = directive; - } - nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), - nodeLinkFn, $compileNode, templateAttrs, jqCollection, childTranscludeFn); - ii = directives.length; - } else if (directive.compile) { - try { - linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); - if (isFunction(linkFn)) { - addLinkFns(null, linkFn, attrStart, attrEnd); - } else if (linkFn) { - addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd); - } - } catch (e) { - $exceptionHandler(e, startingTag($compileNode)); - } - } - - if (directive.terminal) { - nodeLinkFn.terminal = true; - terminalPriority = Math.max(terminalPriority, directive.priority); - } - - } - - nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope; - nodeLinkFn.transclude = transcludeDirective && childTranscludeFn; - - // might be normal or delayed nodeLinkFn depending on if templateUrl is present - return nodeLinkFn; - - //////////////////// - - function addLinkFns(pre, post, attrStart, attrEnd) { - if (pre) { - if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd); - pre.require = directive.require; - preLinkFns.push(pre); - } - if (post) { - if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); - post.require = directive.require; - postLinkFns.push(post); - } - } - - - function getControllers(require, $element) { - var value, retrievalMethod = 'data', optional = false; - if (isString(require)) { - while((value = require.charAt(0)) == '^' || value == '?') { - require = require.substr(1); - if (value == '^') { - retrievalMethod = 'inheritedData'; - } - optional = optional || value == '?'; - } - value = $element[retrievalMethod]('$' + require + 'Controller'); - if (!value && !optional) { - throw $compileMinErr('ctreq', "Controller '{0}', required by directive '{1}', can't be found!", require, directiveName); - } - return value; - } else if (isArray(require)) { - value = []; - forEach(require, function(require) { - value.push(getControllers(require, $element)); - }); - } - return value; - } - - - function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { - var attrs, $element, i, ii, linkFn, controller; - - if (compileNode === linkNode) { - attrs = templateAttrs; - } else { - attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); - } - $element = attrs.$$element; - - if (newIsolateScopeDirective) { - var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/; - - var parentScope = scope.$parent || scope; - - forEach(newIsolateScopeDirective.scope, function(definition, scopeName) { - var match = definition.match(LOCAL_REGEXP) || [], - attrName = match[3] || scopeName, - optional = (match[2] == '?'), - mode = match[1], // @, =, or & - lastValue, - parentGet, parentSet; - - scope.$$isolateBindings[scopeName] = mode + attrName; - - switch (mode) { - - case '@': { - attrs.$observe(attrName, function(value) { - scope[scopeName] = value; - }); - attrs.$$observers[attrName].$$scope = parentScope; - if( attrs[attrName] ) { - // If the attribute has been provided then we trigger an interpolation to ensure the value is there for use in the link fn - scope[scopeName] = $interpolate(attrs[attrName])(parentScope); - } - break; - } - - case '=': { - if (optional && !attrs[attrName]) { - return; - } - parentGet = $parse(attrs[attrName]); - parentSet = parentGet.assign || function() { - // reset the change, or we will throw this exception on every $digest - lastValue = scope[scopeName] = parentGet(parentScope); - throw $compileMinErr('nonassign', "Expression '{0}' used with directive '{1}' is non-assignable!", - attrs[attrName], newIsolateScopeDirective.name); - }; - lastValue = scope[scopeName] = parentGet(parentScope); - scope.$watch(function parentValueWatch() { - var parentValue = parentGet(parentScope); - - if (parentValue !== scope[scopeName]) { - // we are out of sync and need to copy - if (parentValue !== lastValue) { - // parent changed and it has precedence - lastValue = scope[scopeName] = parentValue; - } else { - // if the parent can be assigned then do so - parentSet(parentScope, parentValue = lastValue = scope[scopeName]); - } - } - return parentValue; - }); - break; - } - - case '&': { - parentGet = $parse(attrs[attrName]); - scope[scopeName] = function(locals) { - return parentGet(parentScope, locals); - }; - break; - } - - default: { - throw $compileMinErr('iscp', "Invalid isolate scope definition for directive '{0}'. Definition: {... {1}: '{2}' ...}", - newIsolateScopeDirective.name, scopeName, definition); - } - } - }); - } - - if (controllerDirectives) { - forEach(controllerDirectives, function(directive) { - var locals = { - $scope: scope, - $element: $element, - $attrs: attrs, - $transclude: boundTranscludeFn - }, controllerInstance; - - controller = directive.controller; - if (controller == '@') { - controller = attrs[directive.name]; - } - - controllerInstance = $controller(controller, locals); - $element.data( - '$' + directive.name + 'Controller', - controllerInstance); - if (directive.controllerAs) { - locals.$scope[directive.controllerAs] = controllerInstance; - } - }); - } - - // PRELINKING - for(i = 0, ii = preLinkFns.length; i < ii; i++) { - try { - linkFn = preLinkFns[i]; - linkFn(scope, $element, attrs, - linkFn.require && getControllers(linkFn.require, $element)); - } catch (e) { - $exceptionHandler(e, startingTag($element)); - } - } - - // RECURSION - childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn); - - // POSTLINKING - for(i = 0, ii = postLinkFns.length; i < ii; i++) { - try { - linkFn = postLinkFns[i]; - linkFn(scope, $element, attrs, - linkFn.require && getControllers(linkFn.require, $element)); - } catch (e) { - $exceptionHandler(e, startingTag($element)); - } - } - } - } - - - /** - * looks up the directive and decorates it with exception handling and proper parameters. We - * call this the boundDirective. - * - * @param {string} name name of the directive to look up. - * @param {string} location The directive must be found in specific format. - * String containing any of theses characters: - * - * * `E`: element name - * * `A': attribute - * * `C`: class - * * `M`: comment - * @returns true if directive was added. - */ - function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName, endAttrName) { - if (name === ignoreDirective) return null; - var match = null; - if (hasDirectives.hasOwnProperty(name)) { - for(var directive, directives = $injector.get(name + Suffix), - i = 0, ii = directives.length; i directive.priority) && - directive.restrict.indexOf(location) != -1) { - if (startAttrName) { - directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); - } - tDirectives.push(directive); - match = directive; - } - } catch(e) { $exceptionHandler(e); } - } - } - return match; - } - - - /** - * When the element is replaced with HTML template then the new attributes - * on the template need to be merged with the existing attributes in the DOM. - * The desired effect is to have both of the attributes present. - * - * @param {object} dst destination attributes (original DOM) - * @param {object} src source attributes (from the directive template) - */ - function mergeTemplateAttributes(dst, src) { - var srcAttr = src.$attr, - dstAttr = dst.$attr, - $element = dst.$$element; - - // reapply the old attributes to the new element - forEach(dst, function(value, key) { - if (key.charAt(0) != '$') { - if (src[key]) { - value += (key === 'style' ? ';' : ' ') + src[key]; - } - dst.$set(key, value, true, srcAttr[key]); - } - }); - - // copy the new attributes on the old attrs object - forEach(src, function(value, key) { - if (key == 'class') { - safeAddClass($element, value); - dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; - } else if (key == 'style') { - $element.attr('style', $element.attr('style') + ';' + value); - } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { - dst[key] = value; - dstAttr[key] = srcAttr[key]; - } - }); - } - - - function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs, - $rootElement, childTranscludeFn) { - var linkQueue = [], - afterTemplateNodeLinkFn, - afterTemplateChildLinkFn, - beforeTemplateCompileNode = $compileNode[0], - origAsyncDirective = directives.shift(), - // The fact that we have to copy and patch the directive seems wrong! - derivedSyncDirective = extend({}, origAsyncDirective, { - controller: null, templateUrl: null, transclude: null, scope: null, replace: null - }), - templateUrl = (isFunction(origAsyncDirective.templateUrl)) - ? origAsyncDirective.templateUrl($compileNode, tAttrs) - : origAsyncDirective.templateUrl; - - $compileNode.html(''); - - $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}). - success(function(content) { - var compileNode, tempTemplateAttrs, $template; - - content = denormalizeTemplate(content); - - if (origAsyncDirective.replace) { - $template = jqLite('
' + trim(content) + '
').contents(); - compileNode = $template[0]; - - if ($template.length != 1 || compileNode.nodeType !== 1) { - throw $compileMinErr('tplrt', "Template for directive '{0}' must have exactly one root element. {1}", - origAsyncDirective.name, templateUrl); - } - - tempTemplateAttrs = {$attr: {}}; - replaceWith($rootElement, $compileNode, compileNode); - collectDirectives(compileNode, directives, tempTemplateAttrs); - mergeTemplateAttributes(tAttrs, tempTemplateAttrs); - } else { - compileNode = beforeTemplateCompileNode; - $compileNode.html(content); - } - - directives.unshift(derivedSyncDirective); - - afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn, $compileNode, origAsyncDirective); - forEach($rootElement, function(node, i) { - if (node == compileNode) { - $rootElement[i] = $compileNode[0]; - } - }); - afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); - - - while(linkQueue.length) { - var scope = linkQueue.shift(), - beforeTemplateLinkNode = linkQueue.shift(), - linkRootElement = linkQueue.shift(), - controller = linkQueue.shift(), - linkNode = $compileNode[0]; - - if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { - // it was cloned therefore we have to clone as well. - linkNode = JQLiteClone(compileNode); - replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); - } - - afterTemplateNodeLinkFn( - beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller), - scope, linkNode, $rootElement, controller - ); - } - linkQueue = null; - }). - error(function(response, code, headers, config) { - throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url); - }); - - return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) { - if (linkQueue) { - linkQueue.push(scope); - linkQueue.push(node); - linkQueue.push(rootElement); - linkQueue.push(controller); - } else { - afterTemplateNodeLinkFn(function() { - beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller); - }, scope, node, rootElement, controller); - } - }; - } - - - /** - * Sorting function for bound directives. - */ - function byPriority(a, b) { - return b.priority - a.priority; - } - - - function assertNoDuplicate(what, previousDirective, directive, element) { - if (previousDirective) { - throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}', - previousDirective.name, directive.name, what, startingTag(element)); - } - } - - - function addTextInterpolateDirective(directives, text) { - var interpolateFn = $interpolate(text, true); - if (interpolateFn) { - directives.push({ - priority: 0, - compile: valueFn(function textInterpolateLinkFn(scope, node) { - var parent = node.parent(), - bindings = parent.data('$binding') || []; - bindings.push(interpolateFn); - safeAddClass(parent.data('$binding', bindings), 'ng-binding'); - scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { - node[0].nodeValue = value; - }); - }) - }); - } - } - - - function getTrustedContext(node, attrNormalizedName) { - // maction[xlink:href] can source SVG. It's not limited to . - if (attrNormalizedName == "xlinkHref" || - (nodeName_(node) != "IMG" && (attrNormalizedName == "src" || - attrNormalizedName == "ngSrc"))) { - return $sce.RESOURCE_URL; - } - } - - - function addAttrInterpolateDirective(node, directives, value, name) { - var interpolateFn = $interpolate(value, true); - - // no interpolation found -> ignore - if (!interpolateFn) return; - - - if (name === "multiple" && nodeName_(node) === "SELECT") { - throw $compileMinErr("selmulti", "Binding to the 'multiple' attribute is not supported. Element: {0}", - startingTag(node)); - } - - directives.push({ - priority: 100, - compile: valueFn(function attrInterpolateLinkFn(scope, element, attr) { - var $$observers = (attr.$$observers || (attr.$$observers = {})); - - if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { - throw $compileMinErr('nodomevents', - "Interpolations for HTML DOM event attributes are disallowed. Please use the ng- " + - "versions (such as ng-click instead of onclick) instead."); - } - - // we need to interpolate again, in case the attribute value has been updated - // (e.g. by another directive's compile function) - interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name)); - - // if attribute was updated so that there is no interpolation going on we don't want to - // register any observers - if (!interpolateFn) return; - - attr[name] = interpolateFn(scope); - ($$observers[name] || ($$observers[name] = [])).$$inter = true; - (attr.$$observers && attr.$$observers[name].$$scope || scope). - $watch(interpolateFn, function interpolateFnWatchAction(value) { - attr.$set(name, value); - }); - }) - }); - } - - - /** - * This is a special jqLite.replaceWith, which can replace items which - * have no parents, provided that the containing jqLite collection is provided. - * - * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes - * in the root of the tree. - * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep the shell, - * but replace its DOM node reference. - * @param {Node} newNode The new DOM node. - */ - function replaceWith($rootElement, elementsToRemove, newNode) { - var firstElementToRemove = elementsToRemove[0], - removeCount = elementsToRemove.length, - parent = firstElementToRemove.parentNode, - i, ii; - - if ($rootElement) { - for(i = 0, ii = $rootElement.length; i < ii; i++) { - if ($rootElement[i] == firstElementToRemove) { - $rootElement[i++] = newNode; - for (var j = i, j2 = j + removeCount - 1, - jj = $rootElement.length; - j < jj; j++, j2++) { - if (j2 < jj) { - $rootElement[j] = $rootElement[j2]; - } else { - delete $rootElement[j]; - } - } - $rootElement.length -= removeCount - 1; - break; - } - } - } - - if (parent) { - parent.replaceChild(newNode, firstElementToRemove); - } - var fragment = document.createDocumentFragment(); - fragment.appendChild(firstElementToRemove); - newNode[jqLite.expando] = firstElementToRemove[jqLite.expando]; - for (var k = 1, kk = elementsToRemove.length; k < kk; k++) { - var element = elementsToRemove[k]; - jqLite(element).remove(); // must do this way to clean up expando - fragment.appendChild(element); - delete elementsToRemove[k]; - } - - elementsToRemove[0] = newNode; - elementsToRemove.length = 1 - } - }]; -} - -var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; -/** - * Converts all accepted directives format into proper directive name. - * All of these will become 'myDirective': - * my:Directive - * my-directive - * x-my-directive - * data-my:directive - * - * Also there is special case for Moz prefix starting with upper case letter. - * @param name Name to normalize - */ -function directiveNormalize(name) { - return camelCase(name.replace(PREFIX_REGEXP, '')); -} - -/** - * @ngdoc object - * @name ng.$compile.directive.Attributes - * @description - * - * A shared object between directive compile / linking functions which contains normalized DOM element - * attributes. The the values reflect current binding state `{{ }}`. The normalization is needed - * since all of these are treated as equivalent in Angular: - * - * - */ - -/** - * @ngdoc property - * @name ng.$compile.directive.Attributes#$attr - * @propertyOf ng.$compile.directive.Attributes - * @returns {object} A map of DOM element attribute names to the normalized name. This is - * needed to do reverse lookup from normalized name back to actual name. - */ - - -/** - * @ngdoc function - * @name ng.$compile.directive.Attributes#$set - * @methodOf ng.$compile.directive.Attributes - * @function - * - * @description - * Set DOM element attribute value. - * - * - * @param {string} name Normalized element attribute name of the property to modify. The name is - * revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr} - * property to the original name. - * @param {string} value Value to set the attribute to. The value can be an interpolated string. - */ - - - -/** - * Closure compiler type information - */ - -function nodesetLinkingFn( - /* angular.Scope */ scope, - /* NodeList */ nodeList, - /* Element */ rootElement, - /* function(Function) */ boundTranscludeFn -){} - -function directiveLinkingFn( - /* nodesetLinkingFn */ nodesetLinkingFn, - /* angular.Scope */ scope, - /* Node */ node, - /* Element */ rootElement, - /* function(Function) */ boundTranscludeFn -){} - -/** - * @ngdoc object - * @name ng.$controllerProvider - * @description - * The {@link ng.$controller $controller service} is used by Angular to create new - * controllers. - * - * This provider allows controller registration via the - * {@link ng.$controllerProvider#register register} method. - */ -function $ControllerProvider() { - var controllers = {}, - CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; - - - /** - * @ngdoc function - * @name ng.$controllerProvider#register - * @methodOf ng.$controllerProvider - * @param {string} name Controller name - * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI - * annotations in the array notation). - */ - this.register = function(name, constructor) { - if (isObject(name)) { - extend(controllers, name) - } else { - controllers[name] = constructor; - } - }; - - - this.$get = ['$injector', '$window', function($injector, $window) { - - /** - * @ngdoc function - * @name ng.$controller - * @requires $injector - * - * @param {Function|string} constructor If called with a function then it's considered to be the - * controller constructor function. Otherwise it's considered to be a string which is used - * to retrieve the controller constructor using the following steps: - * - * * check if a controller with given name is registered via `$controllerProvider` - * * check if evaluating the string on the current scope returns a constructor - * * check `window[constructor]` on the global `window` object - * - * @param {Object} locals Injection locals for Controller. - * @return {Object} Instance of given controller. - * - * @description - * `$controller` service is responsible for instantiating controllers. - * - * It's just a simple call to {@link AUTO.$injector $injector}, but extracted into - * a service, so that one can override this service with {@link https://gist.github.com/1649788 - * BC version}. - */ - return function(expression, locals) { - var instance, match, constructor, identifier; - - if(isString(expression)) { - match = expression.match(CNTRL_REG), - constructor = match[1], - identifier = match[3]; - expression = controllers.hasOwnProperty(constructor) - ? controllers[constructor] - : getter(locals.$scope, constructor, true) || getter($window, constructor, true); - - assertArgFn(expression, constructor, true); - } - - instance = $injector.instantiate(expression, locals); - - if (identifier) { - if (!(locals && typeof locals.$scope == 'object')) { - throw minErr('$controller')('noscp', "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.", constructor || expression.name, identifier); - } - - locals.$scope[identifier] = instance; - } - - return instance; - }; - }]; -} - -/** - * @ngdoc object - * @name ng.$document - * @requires $window - * - * @description - * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document` - * element. - */ -function $DocumentProvider(){ - this.$get = ['$window', function(window){ - return jqLite(window.document); - }]; -} - -/** - * @ngdoc function - * @name ng.$exceptionHandler - * @requires $log - * - * @description - * Any uncaught exception in angular expressions is delegated to this service. - * The default implementation simply delegates to `$log.error` which logs it into - * the browser console. - * - * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by - * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing. - * - * @param {Error} exception Exception associated with the error. - * @param {string=} cause optional information about the context in which - * the error was thrown. - * - */ -function $ExceptionHandlerProvider() { - this.$get = ['$log', function($log) { - return function(exception, cause) { - $log.error.apply($log, arguments); - }; - }]; -} - -/** - * Parse headers into key value object - * - * @param {string} headers Raw headers as a string - * @returns {Object} Parsed headers as key value object - */ -function parseHeaders(headers) { - var parsed = {}, key, val, i; - - if (!headers) return parsed; - - forEach(headers.split('\n'), function(line) { - i = line.indexOf(':'); - key = lowercase(trim(line.substr(0, i))); - val = trim(line.substr(i + 1)); - - if (key) { - if (parsed[key]) { - parsed[key] += ', ' + val; - } else { - parsed[key] = val; - } - } - }); - - return parsed; -} - - -/** - * Returns a function that provides access to parsed headers. - * - * Headers are lazy parsed when first requested. - * @see parseHeaders - * - * @param {(string|Object)} headers Headers to provide access to. - * @returns {function(string=)} Returns a getter function which if called with: - * - * - if called with single an argument returns a single header value or null - * - if called with no arguments returns an object containing all headers. - */ -function headersGetter(headers) { - var headersObj = isObject(headers) ? headers : undefined; - - return function(name) { - if (!headersObj) headersObj = parseHeaders(headers); - - if (name) { - return headersObj[lowercase(name)] || null; - } - - return headersObj; - }; -} - - -/** - * Chain all given functions - * - * This function is used for both request and response transforming - * - * @param {*} data Data to transform. - * @param {function(string=)} headers Http headers getter fn. - * @param {(function|Array.)} fns Function or an array of functions. - * @returns {*} Transformed data. - */ -function transformData(data, headers, fns) { - if (isFunction(fns)) - return fns(data, headers); - - forEach(fns, function(fn) { - data = fn(data, headers); - }); - - return data; -} - - -function isSuccess(status) { - return 200 <= status && status < 300; -} - - -function $HttpProvider() { - var JSON_START = /^\s*(\[|\{[^\{])/, - JSON_END = /[\}\]]\s*$/, - PROTECTION_PREFIX = /^\)\]\}',?\n/, - CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'}; - - var defaults = this.defaults = { - // transform incoming response data - transformResponse: [function(data) { - if (isString(data)) { - // strip json vulnerability protection prefix - data = data.replace(PROTECTION_PREFIX, ''); - if (JSON_START.test(data) && JSON_END.test(data)) - data = fromJson(data, true); - } - return data; - }], - - // transform outgoing request data - transformRequest: [function(d) { - return isObject(d) && !isFile(d) ? toJson(d) : d; - }], - - // default headers - headers: { - common: { - 'Accept': 'application/json, text/plain, */*' - }, - post: CONTENT_TYPE_APPLICATION_JSON, - put: CONTENT_TYPE_APPLICATION_JSON, - patch: CONTENT_TYPE_APPLICATION_JSON - }, - - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN' - }; - - /** - * Are order by request. I.E. they are applied in the same order as - * array on request, but revers order on response. - */ - var interceptorFactories = this.interceptors = []; - /** - * For historical reasons, response interceptors ordered by the order in which - * they are applied to response. (This is in revers to interceptorFactories) - */ - var responseInterceptorFactories = this.responseInterceptors = []; - - this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', '$$urlUtils', - function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector, $$urlUtils) { - - var defaultCache = $cacheFactory('$http'); - - /** - * Interceptors stored in reverse order. Inner interceptors before outer interceptors. - * The reversal is needed so that we can build up the interception chain around the - * server request. - */ - var reversedInterceptors = []; - - forEach(interceptorFactories, function(interceptorFactory) { - reversedInterceptors.unshift(isString(interceptorFactory) - ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); - }); - - forEach(responseInterceptorFactories, function(interceptorFactory, index) { - var responseFn = isString(interceptorFactory) - ? $injector.get(interceptorFactory) - : $injector.invoke(interceptorFactory); - - /** - * Response interceptors go before "around" interceptors (no real reason, just - * had to pick one.) But they are already reversed, so we can't use unshift, hence - * the splice. - */ - reversedInterceptors.splice(index, 0, { - response: function(response) { - return responseFn($q.when(response)); - }, - responseError: function(response) { - return responseFn($q.reject(response)); - } - }); - }); - - - /** - * @ngdoc function - * @name ng.$http - * @requires $httpBackend - * @requires $browser - * @requires $cacheFactory - * @requires $rootScope - * @requires $q - * @requires $injector - * - * @description - * The `$http` service is a core Angular service that facilitates communication with the remote - * HTTP servers via the browser's {@link https://developer.mozilla.org/en/xmlhttprequest - * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}. - * - * For unit testing applications that use `$http` service, see - * {@link ngMock.$httpBackend $httpBackend mock}. - * - * For a higher level of abstraction, please check out the {@link ngResource.$resource - * $resource} service. - * - * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by - * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage - * it is important to familiarize yourself with these APIs and the guarantees they provide. - * - * - * # General usage - * The `$http` service is a function which takes a single argument — a configuration object — - * that is used to generate an HTTP request and returns a {@link ng.$q promise} - * with two $http specific methods: `success` and `error`. - * - *
-     *   $http({method: 'GET', url: '/someUrl'}).
-     *     success(function(data, status, headers, config) {
-     *       // this callback will be called asynchronously
-     *       // when the response is available
-     *     }).
-     *     error(function(data, status, headers, config) {
-     *       // called asynchronously if an error occurs
-     *       // or server returns response with an error status.
-     *     });
-     * 
- * - * Since the returned value of calling the $http function is a `promise`, you can also use - * the `then` method to register callbacks, and these callbacks will receive a single argument – - * an object representing the response. See the API signature and type info below for more - * details. - * - * A response status code between 200 and 299 is considered a success status and - * will result in the success callback being called. Note that if the response is a redirect, - * XMLHttpRequest will transparently follow it, meaning that the error callback will not be - * called for such responses. - * - * # Shortcut methods - * - * Since all invocations of the $http service require passing in an HTTP method and URL, and - * POST/PUT requests require request data to be provided as well, shortcut methods - * were created: - * - *
-     *   $http.get('/someUrl').success(successCallback);
-     *   $http.post('/someUrl', data).success(successCallback);
-     * 
- * - * Complete list of shortcut methods: - * - * - {@link ng.$http#get $http.get} - * - {@link ng.$http#head $http.head} - * - {@link ng.$http#post $http.post} - * - {@link ng.$http#put $http.put} - * - {@link ng.$http#delete $http.delete} - * - {@link ng.$http#jsonp $http.jsonp} - * - * - * # Setting HTTP Headers - * - * The $http service will automatically add certain HTTP headers to all requests. These defaults - * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration - * object, which currently contains this default configuration: - * - * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): - * - `Accept: application/json, text/plain, * / *` - * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) - * - `Content-Type: application/json` - * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) - * - `Content-Type: application/json` - * - * To add or overwrite these defaults, simply add or remove a property from these configuration - * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object - * with the lowercased HTTP method name as the key, e.g. - * `$httpProvider.defaults.headers.get['My-Header']='value'`. - * - * Additionally, the defaults can be set at runtime via the `$http.defaults` object in the same - * fashion. - * - * - * # Transforming Requests and Responses - * - * Both requests and responses can be transformed using transform functions. By default, Angular - * applies these transformations: - * - * Request transformations: - * - * - If the `data` property of the request configuration object contains an object, serialize it into - * JSON format. - * - * Response transformations: - * - * - If XSRF prefix is detected, strip it (see Security Considerations section below). - * - If JSON response is detected, deserialize it using a JSON parser. - * - * To globally augment or override the default transforms, modify the `$httpProvider.defaults.transformRequest` and - * `$httpProvider.defaults.transformResponse` properties. These properties are by default an - * array of transform functions, which allows you to `push` or `unshift` a new transformation function into the - * transformation chain. You can also decide to completely override any default transformations by assigning your - * transformation functions to these properties directly without the array wrapper. - * - * Similarly, to locally override the request/response transforms, augment the `transformRequest` and/or - * `transformResponse` properties of the configuration object passed into `$http`. - * - * - * # Caching - * - * To enable caching, set the configuration property `cache` to `true`. When the cache is - * enabled, `$http` stores the response from the server in local cache. Next time the - * response is served from the cache without sending a request to the server. - * - * Note that even if the response is served from cache, delivery of the data is asynchronous in - * the same way that real requests are. - * - * If there are multiple GET requests for the same URL that should be cached using the same - * cache, but the cache is not populated yet, only one request to the server will be made and - * the remaining requests will be fulfilled using the response from the first request. - * - * A custom default cache built with $cacheFactory can be provided in $http.defaults.cache. - * To skip it, set configuration property `cache` to `false`. - * - * - * # Interceptors - * - * Before you start creating interceptors, be sure to understand the - * {@link ng.$q $q and deferred/promise APIs}. - * - * For purposes of global error handling, authentication, or any kind of synchronous or - * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be - * able to intercept requests before they are handed to the server and - * responses before they are handed over to the application code that - * initiated these requests. The interceptors leverage the {@link ng.$q - * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing. - * - * The interceptors are service factories that are registered with the `$httpProvider` by - * adding them to the `$httpProvider.interceptors` array. The factory is called and - * injected with dependencies (if specified) and returns the interceptor. - * - * There are two kinds of interceptors (and two kinds of rejection interceptors): - * - * * `request`: interceptors get called with http `config` object. The function is free to modify - * the `config` or create a new one. The function needs to return the `config` directly or as a - * promise. - * * `requestError`: interceptor gets called when a previous interceptor threw an error or resolved - * with a rejection. - * * `response`: interceptors get called with http `response` object. The function is free to modify - * the `response` or create a new one. The function needs to return the `response` directly or as a - * promise. - * * `responseError`: interceptor gets called when a previous interceptor threw an error or resolved - * with a rejection. - * - * - *
-     *   // register the interceptor as a service
-     *   $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
-     *     return {
-     *       // optional method
-     *       'request': function(config) {
-     *         // do something on success
-     *         return config || $q.when(config);
-     *       },
-     *
-     *       // optional method
-     *      'requestError': function(rejection) {
-     *         // do something on error
-     *         if (canRecover(rejection)) {
-     *           return responseOrNewPromise
-     *         }
-     *         return $q.reject(rejection);
-     *       },
-     *
-     *
-     *
-     *       // optional method
-     *       'response': function(response) {
-     *         // do something on success
-     *         return response || $q.when(response);
-     *       },
-     *
-     *       // optional method
-     *      'responseError': function(rejection) {
-     *         // do something on error
-     *         if (canRecover(rejection)) {
-     *           return responseOrNewPromise
-     *         }
-     *         return $q.reject(rejection);
-     *       };
-     *     }
-     *   });
-     *
-     *   $httpProvider.interceptors.push('myHttpInterceptor');
-     *
-     *
-     *   // register the interceptor via an anonymous factory
-     *   $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
-     *     return {
-     *      'request': function(config) {
-     *          // same as above
-     *       },
-     *       'response': function(response) {
-     *          // same as above
-     *       }
-     *   });
-     * 
- * - * # Response interceptors (DEPRECATED) - * - * Before you start creating interceptors, be sure to understand the - * {@link ng.$q $q and deferred/promise APIs}. - * - * For purposes of global error handling, authentication or any kind of synchronous or - * asynchronous preprocessing of received responses, it is desirable to be able to intercept - * responses for http requests before they are handed over to the application code that - * initiated these requests. The response interceptors leverage the {@link ng.$q - * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. - * - * The interceptors are service factories that are registered with the $httpProvider by - * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and - * injected with dependencies (if specified) and returns the interceptor — a function that - * takes a {@link ng.$q promise} and returns the original or a new promise. - * - *
-     *   // register the interceptor as a service
-     *   $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
-     *     return function(promise) {
-     *       return promise.then(function(response) {
-     *         // do something on success
-     *       }, function(response) {
-     *         // do something on error
-     *         if (canRecover(response)) {
-     *           return responseOrNewPromise
-     *         }
-     *         return $q.reject(response);
-     *       });
-     *     }
-     *   });
-     *
-     *   $httpProvider.responseInterceptors.push('myHttpInterceptor');
-     *
-     *
-     *   // register the interceptor via an anonymous factory
-     *   $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
-     *     return function(promise) {
-     *       // same as above
-     *     }
-     *   });
-     * 
- * - * - * # Security Considerations - * - * When designing web applications, consider security threats from: - * - * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx - * JSON vulnerability} - * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} - * - * Both server and the client must cooperate in order to eliminate these threats. Angular comes - * pre-configured with strategies that address these issues, but for this to work backend server - * cooperation is required. - * - * ## JSON Vulnerability Protection - * - * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx - * JSON vulnerability} allows third party website to turn your JSON resource URL into - * {@link http://en.wikipedia.org/wiki/JSONP JSONP} request under some conditions. To - * counter this your server can prefix all JSON requests with following string `")]}',\n"`. - * Angular will automatically strip the prefix before processing it as JSON. - * - * For example if your server needs to return: - *
-     * ['one','two']
-     * 
- * - * which is vulnerable to attack, your server can return: - *
-     * )]}',
-     * ['one','two']
-     * 
- * - * Angular will strip the prefix, before processing the JSON. - * - * - * ## Cross Site Request Forgery (XSRF) Protection - * - * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which - * an unauthorized site can gain your user's private data. Angular provides a mechanism - * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie - * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only - * JavaScript that runs on your domain could read the cookie, your server can be assured that - * the XHR came from JavaScript running on your domain. The header will not be set for - * cross-domain requests. - * - * To take advantage of this, your server needs to set a token in a JavaScript readable session - * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the - * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure - * that only JavaScript running on your domain could have sent the request. The token must be - * unique for each user and must be verifiable by the server (to prevent the JavaScript from making - * up its own tokens). We recommend that the token is a digest of your site's authentication - * cookie with a {@link https://en.wikipedia.org/wiki/Salt_(cryptography) salt} for added security. - * - * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName - * properties of either $httpProvider.defaults, or the per-request config object. - * - * - * @param {object} config Object describing the request to be made and how it should be - * processed. The object has following properties: - * - * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) - * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. - * - **params** – `{Object.}` – Map of strings or objects which will be turned to - * `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified. - * - **data** – `{string|Object}` – Data to be sent as the request message data. - * - **headers** – `{Object}` – Map of strings or functions which return strings representing - * HTTP headers to send to the server. If the return value of a function is null, the header will - * not be sent. - * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. - * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. - * - **transformRequest** – `{function(data, headersGetter)|Array.}` – - * transform function or an array of such functions. The transform function takes the http - * request body and headers and returns its transformed (typically serialized) version. - * - **transformResponse** – `{function(data, headersGetter)|Array.}` – - * transform function or an array of such functions. The transform function takes the http - * response body and headers and returns its transformed (typically deserialized) version. - * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the - * GET request, otherwise if a cache instance built with - * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for - * caching. - * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} - * that should abort the request when resolved. - * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the - * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 - * requests with credentials} for more information. - * - **responseType** - `{string}` - see {@link - * https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}. - * - * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the - * standard `then` method and two http specific methods: `success` and `error`. The `then` - * method takes two arguments a success and an error callback which will be called with a - * response object. The `success` and `error` methods take a single argument - a function that - * will be called when the request succeeds or fails respectively. The arguments passed into - * these functions are destructured representation of the response object passed into the - * `then` method. The response object has these properties: - * - * - **data** – `{string|Object}` – The response body transformed with the transform functions. - * - **status** – `{number}` – HTTP status code of the response. - * - **headers** – `{function([headerName])}` – Header getter function. - * - **config** – `{Object}` – The configuration object that was used to generate the request. - * - * @property {Array.} pendingRequests Array of config objects for currently pending - * requests. This is primarily meant to be used for debugging purposes. - * - * - * @example - - -
- - -
- - - -
http status code: {{status}}
-
http response data: {{data}}
-
-
- - function FetchCtrl($scope, $http, $templateCache) { - $scope.method = 'GET'; - $scope.url = 'http-hello.html'; - - $scope.fetch = function() { - $scope.code = null; - $scope.response = null; - - $http({method: $scope.method, url: $scope.url, cache: $templateCache}). - success(function(data, status) { - $scope.status = status; - $scope.data = data; - }). - error(function(data, status) { - $scope.data = data || "Request failed"; - $scope.status = status; - }); - }; - - $scope.updateModel = function(method, url) { - $scope.method = method; - $scope.url = url; - }; - } - - - Hello, $http! - - - it('should make an xhr GET request', function() { - element(':button:contains("Sample GET")').click(); - element(':button:contains("fetch")').click(); - expect(binding('status')).toBe('200'); - expect(binding('data')).toMatch(/Hello, \$http!/); - }); - - it('should make a JSONP request to angularjs.org', function() { - element(':button:contains("Sample JSONP")').click(); - element(':button:contains("fetch")').click(); - expect(binding('status')).toBe('200'); - expect(binding('data')).toMatch(/Super Hero!/); - }); - - it('should make JSONP request to invalid URL and invoke the error handler', - function() { - element(':button:contains("Invalid JSONP")').click(); - element(':button:contains("fetch")').click(); - expect(binding('status')).toBe('0'); - expect(binding('data')).toBe('Request failed'); - }); - -
- */ - function $http(requestConfig) { - var config = { - transformRequest: defaults.transformRequest, - transformResponse: defaults.transformResponse - }; - var headers = mergeHeaders(requestConfig); - - extend(config, requestConfig); - config.headers = headers; - config.method = uppercase(config.method); - - var xsrfValue = $$urlUtils.isSameOrigin(config.url) - ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] - : undefined; - if (xsrfValue) { - headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; - } - - - var serverRequest = function(config) { - headers = config.headers; - var reqData = transformData(config.data, headersGetter(headers), config.transformRequest); - - // strip content-type if data is undefined - if (isUndefined(config.data)) { - forEach(headers, function(value, header) { - if (lowercase(header) === 'content-type') { - delete headers[header]; - } - }); - } - - if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { - config.withCredentials = defaults.withCredentials; - } - - // send request - return sendReq(config, reqData, headers).then(transformResponse, transformResponse); - }; - - var chain = [serverRequest, undefined]; - var promise = $q.when(config); - - // apply interceptors - forEach(reversedInterceptors, function(interceptor) { - if (interceptor.request || interceptor.requestError) { - chain.unshift(interceptor.request, interceptor.requestError); - } - if (interceptor.response || interceptor.responseError) { - chain.push(interceptor.response, interceptor.responseError); - } - }); - - while(chain.length) { - var thenFn = chain.shift(); - var rejectFn = chain.shift(); - - promise = promise.then(thenFn, rejectFn); - } - - promise.success = function(fn) { - promise.then(function(response) { - fn(response.data, response.status, response.headers, config); - }); - return promise; - }; - - promise.error = function(fn) { - promise.then(null, function(response) { - fn(response.data, response.status, response.headers, config); - }); - return promise; - }; - - return promise; - - function transformResponse(response) { - // make a copy since the response must be cacheable - var resp = extend({}, response, { - data: transformData(response.data, response.headers, config.transformResponse) - }); - return (isSuccess(response.status)) - ? resp - : $q.reject(resp); - } - - function mergeHeaders(config) { - var defHeaders = defaults.headers, - reqHeaders = extend({}, config.headers), - defHeaderName, lowercaseDefHeaderName, reqHeaderName; - - defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); - - // execute if header value is function - execHeaders(defHeaders); - execHeaders(reqHeaders); - - // using for-in instead of forEach to avoid unecessary iteration after header has been found - defaultHeadersIteration: - for (defHeaderName in defHeaders) { - lowercaseDefHeaderName = lowercase(defHeaderName); - - for (reqHeaderName in reqHeaders) { - if (lowercase(reqHeaderName) === lowercaseDefHeaderName) { - continue defaultHeadersIteration; - } - } - - reqHeaders[defHeaderName] = defHeaders[defHeaderName]; - } - - return reqHeaders; - - function execHeaders(headers) { - var headerContent; - - forEach(headers, function(headerFn, header) { - if (isFunction(headerFn)) { - headerContent = headerFn(); - if (headerContent != null) { - headers[header] = headerContent; - } else { - delete headers[header]; - } - } - }); - } - } - } - - $http.pendingRequests = []; - - /** - * @ngdoc method - * @name ng.$http#get - * @methodOf ng.$http - * - * @description - * Shortcut method to perform `GET` request. - * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object - */ - - /** - * @ngdoc method - * @name ng.$http#delete - * @methodOf ng.$http - * - * @description - * Shortcut method to perform `DELETE` request. - * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object - */ - - /** - * @ngdoc method - * @name ng.$http#head - * @methodOf ng.$http - * - * @description - * Shortcut method to perform `HEAD` request. - * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object - */ - - /** - * @ngdoc method - * @name ng.$http#jsonp - * @methodOf ng.$http - * - * @description - * Shortcut method to perform `JSONP` request. - * - * @param {string} url Relative or absolute URL specifying the destination of the request. - * Should contain `JSON_CALLBACK` string. - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object - */ - createShortMethods('get', 'delete', 'head', 'jsonp'); - - /** - * @ngdoc method - * @name ng.$http#post - * @methodOf ng.$http - * - * @description - * Shortcut method to perform `POST` request. - * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {*} data Request content - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object - */ - - /** - * @ngdoc method - * @name ng.$http#put - * @methodOf ng.$http - * - * @description - * Shortcut method to perform `PUT` request. - * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {*} data Request content - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object - */ - createShortMethodsWithData('post', 'put'); - - /** - * @ngdoc property - * @name ng.$http#defaults - * @propertyOf ng.$http - * - * @description - * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of - * default headers, withCredentials as well as request and response transformations. - * - * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. - */ - $http.defaults = defaults; - - - return $http; - - - function createShortMethods(names) { - forEach(arguments, function(name) { - $http[name] = function(url, config) { - return $http(extend(config || {}, { - method: name, - url: url - })); - }; - }); - } - - - function createShortMethodsWithData(name) { - forEach(arguments, function(name) { - $http[name] = function(url, data, config) { - return $http(extend(config || {}, { - method: name, - url: url, - data: data - })); - }; - }); - } - - - /** - * Makes the request. - * - * !!! ACCESSES CLOSURE VARS: - * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests - */ - function sendReq(config, reqData, reqHeaders) { - var deferred = $q.defer(), - promise = deferred.promise, - cache, - cachedResp, - url = buildUrl(config.url, config.params); - - $http.pendingRequests.push(config); - promise.then(removePendingReq, removePendingReq); - - - if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') { - cache = isObject(config.cache) ? config.cache - : isObject(defaults.cache) ? defaults.cache - : defaultCache; - } - - if (cache) { - cachedResp = cache.get(url); - if (cachedResp) { - if (cachedResp.then) { - // cached request has already been sent, but there is no response yet - cachedResp.then(removePendingReq, removePendingReq); - return cachedResp; - } else { - // serving from cache - if (isArray(cachedResp)) { - resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2])); - } else { - resolvePromise(cachedResp, 200, {}); - } - } - } else { - // put the promise for the non-transformed response into cache as a placeholder - cache.put(url, promise); - } - } - - // if we won't have the response in cache, send the request to the backend - if (!cachedResp) { - $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, - config.withCredentials, config.responseType); - } - - return promise; - - - /** - * Callback registered to $httpBackend(): - * - caches the response if desired - * - resolves the raw $http promise - * - calls $apply - */ - function done(status, response, headersString) { - if (cache) { - if (isSuccess(status)) { - cache.put(url, [status, response, parseHeaders(headersString)]); - } else { - // remove promise from the cache - cache.remove(url); - } - } - - resolvePromise(response, status, headersString); - if (!$rootScope.$$phase) $rootScope.$apply(); - } - - - /** - * Resolves the raw $http promise. - */ - function resolvePromise(response, status, headers) { - // normalize internal statuses to 0 - status = Math.max(status, 0); - - (isSuccess(status) ? deferred.resolve : deferred.reject)({ - data: response, - status: status, - headers: headersGetter(headers), - config: config - }); - } - - - function removePendingReq() { - var idx = indexOf($http.pendingRequests, config); - if (idx !== -1) $http.pendingRequests.splice(idx, 1); - } - } - - - function buildUrl(url, params) { - if (!params) return url; - var parts = []; - forEachSorted(params, function(value, key) { - if (value == null || value == undefined) return; - if (!isArray(value)) value = [value]; - - forEach(value, function(v) { - if (isObject(v)) { - v = toJson(v); - } - parts.push(encodeUriQuery(key) + '=' + - encodeUriQuery(v)); - }); - }); - return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); - } - - - }]; -} - -var XHR = window.XMLHttpRequest || function() { - try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} - try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} - try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} - throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest."); -}; - - -/** - * @ngdoc object - * @name ng.$httpBackend - * @requires $browser - * @requires $window - * @requires $document - * - * @description - * HTTP backend used by the {@link ng.$http service} that delegates to - * 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 ng.$http $http} or {@link ngResource.$resource $resource}. - * - * During testing this implementation is swapped with {@link ngMock.$httpBackend mock - * $httpBackend} which can be trained with responses. - */ -function $HttpBackendProvider() { - this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { - return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks, - $document[0], $window.location.protocol.replace(':', '')); - }]; -} - -function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) { - // TODO(vojta): fix the signature - return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { - var status; - $browser.$$incOutstandingRequestCount(); - url = url || $browser.url(); - - if (lowercase(method) == 'jsonp') { - var callbackId = '_' + (callbacks.counter++).toString(36); - callbacks[callbackId] = function(data) { - callbacks[callbackId].data = data; - }; - - var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), - function() { - if (callbacks[callbackId].data) { - completeRequest(callback, 200, callbacks[callbackId].data); - } else { - completeRequest(callback, status || -2); - } - delete callbacks[callbackId]; - }); - } else { - var xhr = new XHR(); - xhr.open(method, url, true); - forEach(headers, function(value, key) { - if (value) xhr.setRequestHeader(key, value); - }); - - // In IE6 and 7, this might be called synchronously when xhr.send below is called and the - // response is in the cache. the promise api will ensure that to the app code the api is - // always async - xhr.onreadystatechange = function() { - if (xhr.readyState == 4) { - var responseHeaders = xhr.getAllResponseHeaders(); - - // TODO(vojta): remove once Firefox 21 gets released. - // begin: workaround to overcome Firefox CORS http response headers bug - // https://bugzilla.mozilla.org/show_bug.cgi?id=608735 - // Firefox already patched in nightly. Should land in Firefox 21. - - // CORS "simple response headers" http://www.w3.org/TR/cors/ - var value, - simpleHeaders = ["Cache-Control", "Content-Language", "Content-Type", - "Expires", "Last-Modified", "Pragma"]; - if (!responseHeaders) { - responseHeaders = ""; - forEach(simpleHeaders, function (header) { - var value = xhr.getResponseHeader(header); - if (value) { - responseHeaders += header + ": " + value + "\n"; - } - }); - } - // end of the workaround. - - // responseText is the old-school way of retrieving response (supported by IE8 & 9) - // response and responseType properties were introduced in XHR Level2 spec (supported by IE10) - completeRequest(callback, - status || xhr.status, - (xhr.responseType ? xhr.response : xhr.responseText), - responseHeaders); - } - }; - - if (withCredentials) { - xhr.withCredentials = true; - } - - if (responseType) { - xhr.responseType = responseType; - } - - xhr.send(post || ''); - } - - if (timeout > 0) { - var timeoutId = $browserDefer(timeoutRequest, timeout); - } else if (timeout && timeout.then) { - timeout.then(timeoutRequest); - } - - - function timeoutRequest() { - status = -1; - jsonpDone && jsonpDone(); - xhr && xhr.abort(); - } - - function completeRequest(callback, status, response, headersString) { - // URL_MATCH is defined in src/service/location.js - var protocol = (url.match(SERVER_MATCH) || ['', locationProtocol])[1]; - - // cancel timeout and subsequent timeout promise resolution - timeoutId && $browserDefer.cancel(timeoutId); - jsonpDone = xhr = null; - - // fix status code for file protocol (it's always 0) - status = (protocol == 'file') ? (response ? 200 : 404) : status; - - // normalize IE bug (http://bugs.jquery.com/ticket/1450) - status = status == 1223 ? 204 : status; - - callback(status, response, headersString); - $browser.$$completeOutstandingRequest(noop); - } - }; - - function jsonpReq(url, done) { - // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: - // - fetches local scripts via XHR and evals them - // - adds and immediately removes script elements from the document - var script = rawDocument.createElement('script'), - doneWrapper = function() { - rawDocument.body.removeChild(script); - if (done) done(); - }; - - script.type = 'text/javascript'; - script.src = url; - - if (msie) { - script.onreadystatechange = function() { - if (/loaded|complete/.test(script.readyState)) doneWrapper(); - }; - } else { - script.onload = script.onerror = doneWrapper; - } - - rawDocument.body.appendChild(script); - return doneWrapper; - } -} - -var $interpolateMinErr = minErr('$interpolate'); - -/** - * @ngdoc object - * @name ng.$interpolateProvider - * @function - * - * @description - * - * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. - * - * @example - - - -
- //label// -
-
-
- */ -function $InterpolateProvider() { - var startSymbol = '{{'; - var endSymbol = '}}'; - - /** - * @ngdoc method - * @name ng.$interpolateProvider#startSymbol - * @methodOf ng.$interpolateProvider - * @description - * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. - * - * @param {string=} value new value to set the starting symbol to. - * @returns {string|self} Returns the symbol when used as getter and self if used as setter. - */ - this.startSymbol = function(value){ - if (value) { - startSymbol = value; - return this; - } else { - return startSymbol; - } - }; - - /** - * @ngdoc method - * @name ng.$interpolateProvider#endSymbol - * @methodOf ng.$interpolateProvider - * @description - * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. - * - * @param {string=} value new value to set the ending symbol to. - * @returns {string|self} Returns the symbol when used as getter and self if used as setter. - */ - this.endSymbol = function(value){ - if (value) { - endSymbol = value; - return this; - } else { - return endSymbol; - } - }; - - - this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) { - var startSymbolLength = startSymbol.length, - endSymbolLength = endSymbol.length; - - /** - * @ngdoc function - * @name ng.$interpolate - * @function - * - * @requires $parse - * @requires $sce - * - * @description - * - * Compiles a string with markup into an interpolation function. This service is used by the - * HTML {@link ng.$compile $compile} service for data binding. See - * {@link ng.$interpolateProvider $interpolateProvider} for configuring the - * interpolation markup. - * - * -
-         var $interpolate = ...; // injected
-         var exp = $interpolate('Hello {{name}}!');
-         expect(exp({name:'Angular'}).toEqual('Hello Angular!');
-       
- * - * - * @param {string} text The text with markup to interpolate. - * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have - * embedded expression in order to return an interpolation function. Strings with no - * embedded expression will return null for the interpolation function. - * @param {string=} trustedContext when provided, the returned function passes the interpolated - * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult, - * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that - * provides Strict Contextual Escaping for details. - * @returns {function(context)} an interpolation function which is used to compute the interpolated - * string. The function has these parameters: - * - * * `context`: an object against which any expressions embedded in the strings are evaluated - * against. - * - */ - function $interpolate(text, mustHaveExpression, trustedContext) { - var startIndex, - endIndex, - index = 0, - parts = [], - length = text.length, - hasInterpolation = false, - fn, - exp, - concat = []; - - while(index < length) { - if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && - ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { - (index != startIndex) && parts.push(text.substring(index, startIndex)); - parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex))); - fn.exp = exp; - index = endIndex + endSymbolLength; - hasInterpolation = true; - } else { - // we did not find anything, so we have to add the remainder to the parts array - (index != length) && parts.push(text.substring(index)); - index = length; - } - } - - if (!(length = parts.length)) { - // we added, nothing, must have been an empty string. - parts.push(''); - length = 1; - } - - // Concatenating expressions makes it hard to reason about whether some combination of concatenated - // values are unsafe to use and could easily lead to XSS. By requiring that a single - // expression be used for iframe[src], object[src], etc., we ensure that the value that's used - // is assigned or constructed by some JS code somewhere that is more testable or make it - // obvious that you bound the value to some user controlled value. This helps reduce the load - // when auditing for XSS issues. - if (trustedContext && parts.length > 1) { - throw $interpolateMinErr('noconcat', - "Error while interpolating: {0}\nStrict Contextual Escaping disallows " + - "interpolations that concatenate multiple expressions when a trusted value is " + - "required. See http://docs.angularjs.org/api/ng.$sce", text); - } - - if (!mustHaveExpression || hasInterpolation) { - concat.length = length; - fn = function(context) { - try { - for(var i = 0, ii = length, part; i|Object.>} search New search params - string or hash object. Hash object - * may contain an array of values, which will be decoded as duplicates in the url. - * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a - * single search parameter. If the value is `null`, the parameter will be deleted. - * - * @return {string} search - */ - search: function(search, paramValue) { - switch (arguments.length) { - case 0: - return this.$$search; - case 1: - if (isString(search)) { - this.$$search = parseKeyValue(search); - } else if (isObject(search)) { - this.$$search = search; - } else { - throw $locationMinErr('isrcharg', 'The first argument of the `$location#search()` call must be a string or an object.'); - } - break; - default: - if (paramValue == undefined || paramValue == null) { - delete this.$$search[search]; - } else { - this.$$search[search] = paramValue; - } - } - - this.$$compose(); - return this; - }, - - /** - * @ngdoc method - * @name ng.$location#hash - * @methodOf ng.$location - * - * @description - * This method is getter / setter. - * - * Return hash fragment when called without any parameter. - * - * Change hash fragment when called with parameter and return `$location`. - * - * @param {string=} hash New hash fragment - * @return {string} hash - */ - hash: locationGetterSetter('$$hash', identity), - - /** - * @ngdoc method - * @name ng.$location#replace - * @methodOf ng.$location - * - * @description - * If called, all changes to $location during current `$digest` will be replacing current history - * record, instead of adding new one. - */ - replace: function() { - this.$$replace = true; - return this; - } -}; - -function locationGetter(property) { - return function() { - return this[property]; - }; -} - - -function locationGetterSetter(property, preprocess) { - return function(value) { - if (isUndefined(value)) - return this[property]; - - this[property] = preprocess(value); - this.$$compose(); - - return this; - }; -} - - -/** - * @ngdoc object - * @name ng.$location - * - * @requires $browser - * @requires $sniffer - * @requires $rootElement - * - * @description - * The $location service parses the URL in the browser address bar (based on the - * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL - * available to your application. Changes to the URL in the address bar are reflected into - * $location service and changes to $location are reflected into the browser address bar. - * - * **The $location service:** - * - * - Exposes the current URL in the browser address bar, so you can - * - Watch and observe the URL. - * - Change the URL. - * - Synchronizes the URL with the browser when the user - * - Changes the address bar. - * - Clicks the back or forward button (or clicks a History link). - * - Clicks on a link. - * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). - * - * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular - * Services: Using $location} - */ - -/** - * @ngdoc object - * @name ng.$locationProvider - * @description - * Use the `$locationProvider` to configure how the application deep linking paths are stored. - */ -function $LocationProvider(){ - var hashPrefix = '', - html5Mode = false; - - /** - * @ngdoc property - * @name ng.$locationProvider#hashPrefix - * @methodOf ng.$locationProvider - * @description - * @param {string=} prefix Prefix for hash part (containing path and search) - * @returns {*} current value if used as getter or itself (chaining) if used as setter - */ - this.hashPrefix = function(prefix) { - if (isDefined(prefix)) { - hashPrefix = prefix; - return this; - } else { - return hashPrefix; - } - }; - - /** - * @ngdoc property - * @name ng.$locationProvider#html5Mode - * @methodOf ng.$locationProvider - * @description - * @param {string=} mode Use HTML5 strategy if available. - * @returns {*} current value if used as getter or itself (chaining) if used as setter - */ - this.html5Mode = function(mode) { - if (isDefined(mode)) { - html5Mode = mode; - return this; - } else { - return html5Mode; - } - }; - - this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', - function( $rootScope, $browser, $sniffer, $rootElement) { - var $location, - LocationMode, - baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to '' - initialUrl = $browser.url(), - appBase; - - if (html5Mode) { - appBase = serverBase(initialUrl) + (baseHref || '/'); - LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; - } else { - appBase = stripHash(initialUrl); - LocationMode = LocationHashbangUrl; - } - $location = new LocationMode(appBase, '#' + hashPrefix); - $location.$$parse($location.$$rewrite(initialUrl)); - - $rootElement.on('click', function(event) { - // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) - // currently we open nice url link and redirect then - - if (event.ctrlKey || event.metaKey || event.which == 2) return; - - var elm = jqLite(event.target); - - // traverse the DOM up to find first A tag - while (lowercase(elm[0].nodeName) !== 'a') { - // ignore rewriting if no A tag (reached root element, or no parent - removed from document) - if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; - } - - var absHref = elm.prop('href'); - var rewrittenUrl = $location.$$rewrite(absHref); - - if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) { - event.preventDefault(); - if (rewrittenUrl != $browser.url()) { - // update location manually - $location.$$parse(rewrittenUrl); - $rootScope.$apply(); - // hack to work around FF6 bug 684208 when scenario runner clicks on links - window.angular['ff-684208-preventDefault'] = true; - } - } - }); - - - // rewrite hashbang url <> html5 url - if ($location.absUrl() != initialUrl) { - $browser.url($location.absUrl(), true); - } - - // update $location when $browser url changes - $browser.onUrlChange(function(newUrl) { - if ($location.absUrl() != newUrl) { - if ($rootScope.$broadcast('$locationChangeStart', newUrl, $location.absUrl()).defaultPrevented) { - $browser.url($location.absUrl()); - return; - } - $rootScope.$evalAsync(function() { - var oldUrl = $location.absUrl(); - - $location.$$parse(newUrl); - afterLocationChange(oldUrl); - }); - if (!$rootScope.$$phase) $rootScope.$digest(); - } - }); - - // update browser - var changeCounter = 0; - $rootScope.$watch(function $locationWatch() { - var oldUrl = $browser.url(); - var currentReplace = $location.$$replace; - - if (!changeCounter || oldUrl != $location.absUrl()) { - changeCounter++; - $rootScope.$evalAsync(function() { - if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl). - defaultPrevented) { - $location.$$parse(oldUrl); - } else { - $browser.url($location.absUrl(), currentReplace); - afterLocationChange(oldUrl); - } - }); - } - $location.$$replace = false; - - return changeCounter; - }); - - return $location; - - function afterLocationChange(oldUrl) { - $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl); - } -}]; -} - -/** - * @ngdoc object - * @name ng.$log - * @requires $window - * - * @description - * Simple service for logging. Default implementation writes the message - * into the browser's console (if present). - * - * The main purpose of this service is to simplify debugging and troubleshooting. - * - * @example - - - function LogCtrl($scope, $log) { - $scope.$log = $log; - $scope.message = 'Hello World!'; - } - - -
-

Reload this page with open console, enter text and hit the log button...

- Message: - - - - - -
-
-
- */ - -/** - * @ngdoc object - * @name ng.$logProvider - * @description - * Use the `$logProvider` to configure how the application logs messages - */ -function $LogProvider(){ - var debug = true, - self = this; - - /** - * @ngdoc property - * @name ng.$logProvider#debugEnabled - * @methodOf ng.$logProvider - * @description - * @param {string=} flag enable or disable debug level messages - * @returns {*} current value if used as getter or itself (chaining) if used as setter - */ - this.debugEnabled = function(flag) { - if (isDefined(flag)) { - debug = flag; - return this; - } else { - return debug; - } - }; - - this.$get = ['$window', function($window){ - return { - /** - * @ngdoc method - * @name ng.$log#log - * @methodOf ng.$log - * - * @description - * Write a log message - */ - log: consoleLog('log'), - - /** - * @ngdoc method - * @name ng.$log#info - * @methodOf ng.$log - * - * @description - * Write an information message - */ - info: consoleLog('info'), - - /** - * @ngdoc method - * @name ng.$log#warn - * @methodOf ng.$log - * - * @description - * Write a warning message - */ - warn: consoleLog('warn'), - - /** - * @ngdoc method - * @name ng.$log#error - * @methodOf ng.$log - * - * @description - * Write an error message - */ - error: consoleLog('error'), - - /** - * @ngdoc method - * @name ng.$log#debug - * @methodOf ng.$log - * - * @description - * Write a debug message - */ - debug: (function () { - var fn = consoleLog('debug'); - - return function() { - if (debug) { - fn.apply(self, arguments); - } - } - }()) - }; - - function formatError(arg) { - if (arg instanceof Error) { - if (arg.stack) { - arg = (arg.message && arg.stack.indexOf(arg.message) === -1) - ? 'Error: ' + arg.message + '\n' + arg.stack - : arg.stack; - } else if (arg.sourceURL) { - arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; - } - } - return arg; - } - - function consoleLog(type) { - var console = $window.console || {}, - logFn = console[type] || console.log || noop; - - if (logFn.apply) { - return function() { - var args = []; - forEach(arguments, function(arg) { - args.push(formatError(arg)); - }); - return logFn.apply(console, args); - }; - } - - // we are IE which either doesn't have window.console => this is noop and we do nothing, - // or we are IE where console.log doesn't have apply so we log at least first 2 args - return function(arg1, arg2) { - logFn(arg1, arg2); - } - } - }]; -} - -var $parseMinErr = minErr('$parse'); - -// Sandboxing Angular Expressions -// ------------------------------ -// Angular expressions are generally considered safe because these expressions only have direct access to $scope and -// locals. However, one can obtain the ability to execute arbitrary JS code by obtaining a reference to native JS -// functions such as the Function constructor. -// -// As an example, consider the following Angular expression: -// -// {}.toString.constructor(alert("evil JS code")) -// -// We want to prevent this type of access. For the sake of performance, during the lexing phase we disallow any "dotted" -// access to any member named "constructor". -// -// For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor while evaluating -// For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor while evaluating -// the expression, which is a stronger but more expensive test. Since reflective calls are expensive anyway, this is not -// such a big deal compared to static dereferencing. -// -// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits against the -// expression language, but not to prevent exploits that were enabled by exposing sensitive JavaScript or browser apis -// on Scope. Exposing such objects on a Scope is never a good practice and therefore we are not even trying to protect -// against interaction with an object explicitly exposed in this way. -// -// A developer could foil the name check by aliasing the Function constructor under a different name on the scope. -// -// In general, it is not possible to access a Window object from an angular expression unless a window or some DOM -// object that has a reference to window is published onto a Scope. - -function ensureSafeMemberName(name, fullExpression) { - if (name === "constructor") { - throw $parseMinErr('isecfld', - 'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}', fullExpression); - } - return name; -}; - -function ensureSafeObject(obj, fullExpression) { - // nifty check if obj is Function that is fast and works across iframes and other contexts - if (obj && obj.constructor === obj) { - throw $parseMinErr('isecfn', - 'Referencing Function in Angular expressions is disallowed! Expression: {0}', fullExpression); - } else { - return obj; - } -} - - -var OPERATORS = { - 'null':function(){return null;}, - 'true':function(){return true;}, - 'false':function(){return false;}, - undefined:noop, - '+':function(self, locals, a,b){ - a=a(self, locals); b=b(self, locals); - if (isDefined(a)) { - if (isDefined(b)) { - return a + b; - } - return a; - } - return isDefined(b)?b:undefined;}, - '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, - '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, - '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, - '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, - '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, - '=':noop, - '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);}, - '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);}, - '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, - '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, - '<':function(self, locals, a,b){return a(self, locals)':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, - '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, - '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, - '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, - '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, - '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, -// '|':function(self, locals, a,b){return a|b;}, - '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));}, - '!':function(self, locals, a){return !a(self, locals);} -}; -var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; - -function lex(text, csp){ - var tokens = [], - token, - index = 0, - json = [], - ch, - lastCh = ':'; // can start regexp - - while (index < text.length) { - ch = text.charAt(index); - if (is('"\'')) { - readString(ch); - } else if (isNumber(ch) || is('.') && isNumber(peek())) { - readNumber(); - } else if (isIdent(ch)) { - readIdent(); - // identifiers can only be if the preceding char was a { or , - if (was('{,') && json[0]=='{' && - (token=tokens[tokens.length-1])) { - token.json = token.text.indexOf('.') == -1; - } - } else if (is('(){}[].,;:?')) { - tokens.push({ - index:index, - text:ch, - json:(was(':[,') && is('{[')) || is('}]:,') - }); - if (is('{[')) json.unshift(ch); - if (is('}]')) json.shift(); - index++; - } else if (isWhitespace(ch)) { - index++; - continue; - } else { - var ch2 = ch + peek(), - ch3 = ch2 + peek(2), - fn = OPERATORS[ch], - fn2 = OPERATORS[ch2], - fn3 = OPERATORS[ch3]; - if (fn3) { - tokens.push({index:index, text:ch3, fn:fn3}); - index += 3; - } else if (fn2) { - tokens.push({index:index, text:ch2, fn:fn2}); - index += 2; - } else if (fn) { - tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); - index += 1; - } else { - throwError("Unexpected next character ", index, index+1); - } - } - lastCh = ch; - } - return tokens; - - function is(chars) { - return chars.indexOf(ch) != -1; - } - - function was(chars) { - return chars.indexOf(lastCh) != -1; - } - - function peek(i) { - var num = i || 1; - return index + num < text.length ? text.charAt(index + num) : false; - } - function isNumber(ch) { - return '0' <= ch && ch <= '9'; - } - function isWhitespace(ch) { - return ch == ' ' || ch == '\r' || ch == '\t' || - ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 - } - function isIdent(ch) { - return 'a' <= ch && ch <= 'z' || - 'A' <= ch && ch <= 'Z' || - '_' == ch || ch == '$'; - } - function isExpOperator(ch) { - return ch == '-' || ch == '+' || isNumber(ch); - } - - function throwError(error, start, end) { - end = end || index; - var colStr = (isDefined(start) ? - "s " + start + "-" + index + " [" + text.substring(start, end) + "]" - : " " + end); - throw $parseMinErr('lexerr', "Lexer Error: {0} at column{1} in expression [{2}].", - error, colStr, text); - } - - function readNumber() { - var number = ""; - var start = index; - while (index < text.length) { - var ch = lowercase(text.charAt(index)); - if (ch == '.' || isNumber(ch)) { - number += ch; - } else { - var peekCh = peek(); - if (ch == 'e' && isExpOperator(peekCh)) { - number += ch; - } else if (isExpOperator(ch) && - peekCh && isNumber(peekCh) && - number.charAt(number.length - 1) == 'e') { - number += ch; - } else if (isExpOperator(ch) && - (!peekCh || !isNumber(peekCh)) && - number.charAt(number.length - 1) == 'e') { - throwError('Invalid exponent'); - } else { - break; - } - } - index++; - } - number = 1 * number; - tokens.push({index:start, text:number, json:true, - fn:function() {return number;}}); - } - function readIdent() { - var ident = "", - start = index, - lastDot, peekIndex, methodName, ch; - - while (index < text.length) { - ch = text.charAt(index); - if (ch == '.' || isIdent(ch) || isNumber(ch)) { - if (ch == '.') lastDot = index; - ident += ch; - } else { - break; - } - index++; - } - - //check if this is not a method invocation and if it is back out to last dot - if (lastDot) { - peekIndex = index; - while(peekIndex < text.length) { - ch = text.charAt(peekIndex); - if (ch == '(') { - methodName = ident.substr(lastDot - start + 1); - ident = ident.substr(0, lastDot - start); - index = peekIndex; - break; - } - if(isWhitespace(ch)) { - peekIndex++; - } else { - break; - } - } - } - - - var token = { - index:start, - text:ident - }; - - if (OPERATORS.hasOwnProperty(ident)) { - token.fn = token.json = OPERATORS[ident]; - } else { - var getter = getterFn(ident, csp, text); - token.fn = extend(function(self, locals) { - return (getter(self, locals)); - }, { - assign: function(self, value) { - return setter(self, ident, value, text); - } - }); - } - - tokens.push(token); - - if (methodName) { - tokens.push({ - index:lastDot, - text: '.', - json: false - }); - tokens.push({ - index: lastDot + 1, - text: methodName, - json: false - }); - } - } - - function readString(quote) { - var start = index; - index++; - var string = ""; - var rawString = quote; - var escape = false; - while (index < text.length) { - var ch = text.charAt(index); - rawString += ch; - if (escape) { - if (ch == 'u') { - var hex = text.substring(index + 1, index + 5); - if (!hex.match(/[\da-f]{4}/i)) - throwError( "Invalid unicode escape [\\u" + hex + "]"); - index += 4; - string += String.fromCharCode(parseInt(hex, 16)); - } else { - var rep = ESCAPE[ch]; - if (rep) { - string += rep; - } else { - string += ch; - } - } - escape = false; - } else if (ch == '\\') { - escape = true; - } else if (ch == quote) { - index++; - tokens.push({ - index:start, - text:rawString, - string:string, - json:true, - fn:function() { return string; } - }); - return; - } else { - string += ch; - } - index++; - } - throwError("Unterminated quote", start); - } -} - -///////////////////////////////////////// - -function parser(text, json, $filter, csp){ - var ZERO = valueFn(0), - value, - tokens = lex(text, csp), - assignment = _assignment, - functionCall = _functionCall, - fieldAccess = _fieldAccess, - objectIndex = _objectIndex, - filterChain = _filterChain; - - if(json){ - // The extra level of aliasing is here, just in case the lexer misses something, so that - // we prevent any accidental execution in JSON. - assignment = logicalOR; - functionCall = - fieldAccess = - objectIndex = - filterChain = - function() { throwError("is not valid json", {text:text, index:0}); }; - value = primary(); - } else { - value = statements(); - } - if (tokens.length !== 0) { - throwError("is an unexpected token", tokens[0]); - } - value.literal = !!value.literal; - value.constant = !!value.constant; - return value; - - /////////////////////////////////// - function throwError(msg, token) { - throw $parseMinErr('syntax', - "Syntax Error: Token '{0}' {1} at column {2} of the expression [{3}] starting at [{4}].", - token.text, msg, (token.index + 1), text, text.substring(token.index)); - } - - function peekToken() { - if (tokens.length === 0) - throw $parseMinErr('ueoe', "Unexpected end of expression: {0}", text); - return tokens[0]; - } - - function peek(e1, e2, e3, e4) { - if (tokens.length > 0) { - var token = tokens[0]; - var t = token.text; - if (t==e1 || t==e2 || t==e3 || t==e4 || - (!e1 && !e2 && !e3 && !e4)) { - return token; - } - } - return false; - } - - function expect(e1, e2, e3, e4){ - var token = peek(e1, e2, e3, e4); - if (token) { - if (json && !token.json) { - throwError("is not valid json", token); - } - tokens.shift(); - return token; - } - return false; - } - - function consume(e1){ - if (!expect(e1)) { - throwError("is unexpected, expecting [" + e1 + "]", peek()); - } - } - - function unaryFn(fn, right) { - return extend(function(self, locals) { - return fn(self, locals, right); - }, { - constant:right.constant - }); - } - - function ternaryFn(left, middle, right){ - return extend(function(self, locals){ - return left(self, locals) ? middle(self, locals) : right(self, locals); - }, { - constant: left.constant && middle.constant && right.constant - }); - } - - function binaryFn(left, fn, right) { - return extend(function(self, locals) { - return fn(self, locals, left, right); - }, { - constant:left.constant && right.constant - }); - } - - function statements() { - var statements = []; - while(true) { - if (tokens.length > 0 && !peek('}', ')', ';', ']')) - statements.push(filterChain()); - if (!expect(';')) { - // optimize for the common case where there is only one statement. - // TODO(size): maybe we should not support multiple statements? - return statements.length == 1 - ? statements[0] - : function(self, locals){ - var value; - for ( var i = 0; i < statements.length; i++) { - var statement = statements[i]; - if (statement) - value = statement(self, locals); - } - return value; - }; - } - } - } - - function _filterChain() { - var left = expression(); - var token; - while(true) { - if ((token = expect('|'))) { - left = binaryFn(left, token.fn, filter()); - } else { - return left; - } - } - } - - function filter() { - var token = expect(); - var fn = $filter(token.text); - var argsFn = []; - while(true) { - if ((token = expect(':'))) { - argsFn.push(expression()); - } else { - var fnInvoke = function(self, locals, input){ - var args = [input]; - for ( var i = 0; i < argsFn.length; i++) { - args.push(argsFn[i](self, locals)); - } - return fn.apply(self, args); - }; - return function() { - return fnInvoke; - }; - } - } - } - - function expression() { - return assignment(); - } - - function _assignment() { - var left = ternary(); - var right; - var token; - if ((token = expect('='))) { - if (!left.assign) { - throwError("implies assignment but [" + - text.substring(0, token.index) + "] can not be assigned to", token); - } - right = ternary(); - return function(scope, locals){ - return left.assign(scope, right(scope, locals), locals); - }; - } else { - return left; - } - } - - function ternary() { - var left = logicalOR(); - var middle; - var token; - if((token = expect('?'))){ - middle = ternary(); - if((token = expect(':'))){ - return ternaryFn(left, middle, ternary()); - } - else { - throwError('expected :', token); - } - } - else { - return left; - } - } - - function logicalOR() { - var left = logicalAND(); - var token; - while(true) { - if ((token = expect('||'))) { - left = binaryFn(left, token.fn, logicalAND()); - } else { - return left; - } - } - } - - function logicalAND() { - var left = equality(); - var token; - if ((token = expect('&&'))) { - left = binaryFn(left, token.fn, logicalAND()); - } - return left; - } - - function equality() { - var left = relational(); - var token; - if ((token = expect('==','!=','===','!=='))) { - left = binaryFn(left, token.fn, equality()); - } - return left; - } - - function relational() { - var left = additive(); - var token; - if ((token = expect('<', '>', '<=', '>='))) { - left = binaryFn(left, token.fn, relational()); - } - return left; - } - - function additive() { - var left = multiplicative(); - var token; - while ((token = expect('+','-'))) { - left = binaryFn(left, token.fn, multiplicative()); - } - return left; - } - - function multiplicative() { - var left = unary(); - var token; - while ((token = expect('*','/','%'))) { - left = binaryFn(left, token.fn, unary()); - } - return left; - } - - function unary() { - var token; - if (expect('+')) { - return primary(); - } else if ((token = expect('-'))) { - return binaryFn(ZERO, token.fn, unary()); - } else if ((token = expect('!'))) { - return unaryFn(token.fn, unary()); - } else { - return primary(); - } - } - - - function primary() { - var primary; - if (expect('(')) { - primary = filterChain(); - consume(')'); - } else if (expect('[')) { - primary = arrayDeclaration(); - } else if (expect('{')) { - primary = object(); - } else { - var token = expect(); - primary = token.fn; - if (!primary) { - throwError("not a primary expression", token); - } - if (token.json) { - primary.constant = primary.literal = true; - } - } - - var next, context; - while ((next = expect('(', '[', '.'))) { - if (next.text === '(') { - primary = functionCall(primary, context); - context = null; - } else if (next.text === '[') { - context = primary; - primary = objectIndex(primary); - } else if (next.text === '.') { - context = primary; - primary = fieldAccess(primary); - } else { - throwError("IMPOSSIBLE"); - } - } - return primary; - } - - function _fieldAccess(object) { - var field = expect().text; - var getter = getterFn(field, csp, text); - return extend( - function(scope, locals, self) { - return getter(self || object(scope, locals), locals); - }, - { - assign:function(scope, value, locals) { - return setter(object(scope, locals), field, value, text); - } - } - ); - } - - function _objectIndex(obj) { - var indexFn = expression(); - consume(']'); - return extend( - function(self, locals){ - var o = obj(self, locals), - i = indexFn(self, locals), - v, p; - - if (!o) return undefined; - v = ensureSafeObject(o[i], text); - if (v && v.then) { - p = v; - if (!('$$v' in v)) { - p.$$v = undefined; - p.then(function(val) { p.$$v = val; }); - } - v = v.$$v; - } - return v; - }, { - assign:function(self, value, locals){ - var key = indexFn(self, locals); - // prevent overwriting of Function.constructor which would break ensureSafeObject check - return ensureSafeObject(obj(self, locals), text)[key] = value; - } - }); - } - - function _functionCall(fn, contextGetter) { - var argsFn = []; - if (peekToken().text != ')') { - do { - argsFn.push(expression()); - } while (expect(',')); - } - consume(')'); - return function(scope, locals){ - var args = [], - context = contextGetter ? contextGetter(scope, locals) : scope; - - for ( var i = 0; i < argsFn.length; i++) { - args.push(argsFn[i](scope, locals)); - } - var fnPtr = fn(scope, locals, context) || noop; - // IE stupidity! - return fnPtr.apply - ? fnPtr.apply(context, args) - : fnPtr(args[0], args[1], args[2], args[3], args[4]); - }; - } - - // This is used with json array declaration - function arrayDeclaration () { - var elementFns = []; - var allConstant = true; - if (peekToken().text != ']') { - do { - var elementFn = expression(); - elementFns.push(elementFn); - if (!elementFn.constant) { - allConstant = false; - } - } while (expect(',')); - } - consume(']'); - return extend(function(self, locals){ - var array = []; - for ( var i = 0; i < elementFns.length; i++) { - array.push(elementFns[i](self, locals)); - } - return array; - }, { - literal:true, - constant:allConstant - }); - } - - function object () { - var keyValues = []; - var allConstant = true; - if (peekToken().text != '}') { - do { - var token = expect(), - key = token.string || token.text; - consume(":"); - var value = expression(); - keyValues.push({key:key, value:value}); - if (!value.constant) { - allConstant = false; - } - } while (expect(',')); - } - consume('}'); - return extend(function(self, locals){ - var object = {}; - for ( var i = 0; i < keyValues.length; i++) { - var keyValue = keyValues[i]; - object[keyValue.key] = keyValue.value(self, locals); - } - return object; - }, { - literal:true, - constant:allConstant - }); - } -} - -////////////////////////////////////////////////// -// Parser helper functions -////////////////////////////////////////////////// - -function setter(obj, path, setValue, fullExp) { - var element = path.split('.'), key; - for (var i = 0; element.length > 1; i++) { - key = ensureSafeMemberName(element.shift(), fullExp); - var propertyObj = obj[key]; - if (!propertyObj) { - propertyObj = {}; - obj[key] = propertyObj; - } - obj = propertyObj; - if (obj.then) { - if (!("$$v" in obj)) { - (function(promise) { - promise.then(function(val) { promise.$$v = val; }); } - )(obj); - } - if (obj.$$v === undefined) { - obj.$$v = {}; - } - obj = obj.$$v; - } - } - key = ensureSafeMemberName(element.shift(), fullExp); - obj[key] = setValue; - return setValue; -} - -var getterFnCache = {}; - -/** - * Implementation of the "Black Hole" variant from: - * - http://jsperf.com/angularjs-parse-getter/4 - * - http://jsperf.com/path-evaluation-simplified/7 - */ -function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp) { - ensureSafeMemberName(key0, fullExp); - ensureSafeMemberName(key1, fullExp); - ensureSafeMemberName(key2, fullExp); - ensureSafeMemberName(key3, fullExp); - ensureSafeMemberName(key4, fullExp); - return function(scope, locals) { - var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, - promise; - - if (pathVal === null || pathVal === undefined) return pathVal; - - pathVal = pathVal[key0]; - if (pathVal && pathVal.then) { - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - if (!key1 || pathVal === null || pathVal === undefined) return pathVal; - - pathVal = pathVal[key1]; - if (pathVal && pathVal.then) { - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - if (!key2 || pathVal === null || pathVal === undefined) return pathVal; - - pathVal = pathVal[key2]; - if (pathVal && pathVal.then) { - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - if (!key3 || pathVal === null || pathVal === undefined) return pathVal; - - pathVal = pathVal[key3]; - if (pathVal && pathVal.then) { - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - if (!key4 || pathVal === null || pathVal === undefined) return pathVal; - - pathVal = pathVal[key4]; - if (pathVal && pathVal.then) { - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - return pathVal; - }; -} - -function getterFn(path, csp, fullExp) { - if (getterFnCache.hasOwnProperty(path)) { - return getterFnCache[path]; - } - - var pathKeys = path.split('.'), - pathKeysLength = pathKeys.length, - fn; - - if (csp) { - fn = (pathKeysLength < 6) - ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp) - : function(scope, locals) { - var i = 0, val; - do { - val = cspSafeGetterFn( - pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], fullExp - )(scope, locals); - - locals = undefined; // clear after first iteration - scope = val; - } while (i < pathKeysLength); - return val; - } - } else { - var code = 'var l, fn, p;\n'; - forEach(pathKeys, function(key, index) { - ensureSafeMemberName(key, fullExp); - code += 'if(s === null || s === undefined) return s;\n' + - 'l=s;\n' + - 's='+ (index - // we simply dereference 's' on any .dot notation - ? 's' - // but if we are first then we check locals first, and if so read it first - : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' + - 'if (s && s.then) {\n' + - ' if (!("$$v" in s)) {\n' + - ' p=s;\n' + - ' p.$$v = undefined;\n' + - ' p.then(function(v) {p.$$v=v;});\n' + - '}\n' + - ' s=s.$$v\n' + - '}\n'; - }); - code += 'return s;'; - fn = Function('s', 'k', code); // s=scope, k=locals - fn.toString = function() { return code; }; - } - - return getterFnCache[path] = fn; -} - -/////////////////////////////////// - -/** - * @ngdoc function - * @name ng.$parse - * @function - * - * @description - * - * Converts Angular {@link guide/expression expression} into a function. - * - *
- *   var getter = $parse('user.name');
- *   var setter = getter.assign;
- *   var context = {user:{name:'angular'}};
- *   var locals = {user:{name:'local'}};
- *
- *   expect(getter(context)).toEqual('angular');
- *   setter(context, 'newValue');
- *   expect(context.user.name).toEqual('newValue');
- *   expect(getter(context, locals)).toEqual('local');
- * 
- * - * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - * - * The returned function also has the following properties: - * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript - * literal. - * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript - * constant literals. - * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be - * set to a function to change its value on the given context. - * - */ -function $ParseProvider() { - var cache = {}; - this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { - return function(exp) { - switch(typeof exp) { - case 'string': - return cache.hasOwnProperty(exp) - ? cache[exp] - : cache[exp] = parser(exp, false, $filter, $sniffer.csp); - case 'function': - return exp; - default: - return noop; - } - }; - }]; -} - -/** - * @ngdoc service - * @name ng.$q - * @requires $rootScope - * - * @description - * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). - * - * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an - * interface for interacting with an object that represents the result of an action that is - * performed asynchronously, and may or may not be finished at any given point in time. - * - * From the perspective of dealing with error handling, deferred and promise APIs are to - * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. - * - *
- *   // for the purpose of this example let's assume that variables `$q` and `scope` are
- *   // available in the current lexical scope (they could have been injected or passed in).
- *
- *   function asyncGreet(name) {
- *     var deferred = $q.defer();
- *
- *     setTimeout(function() {
- *       // since this fn executes async in a future turn of the event loop, we need to wrap
- *       // our code into an $apply call so that the model changes are properly observed.
- *       scope.$apply(function() {
- *         if (okToGreet(name)) {
- *           deferred.resolve('Hello, ' + name + '!');
- *         } else {
- *           deferred.reject('Greeting ' + name + ' is not allowed.');
- *         }
- *       });
- *     }, 1000);
- *
- *     return deferred.promise;
- *   }
- *
- *   var promise = asyncGreet('Robin Hood');
- *   promise.then(function(greeting) {
- *     alert('Success: ' + greeting);
- *   }, function(reason) {
- *     alert('Failed: ' + reason);
- *   });
- * 
- * - * At first it might not be obvious why this extra complexity is worth the trouble. The payoff - * comes in the way of - * [guarantees that promise and deferred APIs make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md). - * - * Additionally the promise api allows for composition that is very hard to do with the - * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. - * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the - * section on serial or parallel joining of promises. - * - * - * # The Deferred API - * - * A new instance of deferred is constructed by calling `$q.defer()`. - * - * The purpose of the deferred object is to expose the associated Promise instance as well as APIs - * that can be used for signaling the successful or unsuccessful completion of the task. - * - * **Methods** - * - * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection - * constructed via `$q.reject`, the promise will be rejected instead. - * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to - * resolving it with a rejection constructed via `$q.reject`. - * - * **Properties** - * - * - promise – `{Promise}` – promise object associated with this deferred. - * - * - * # The Promise API - * - * A new promise instance is created when a deferred instance is created and can be retrieved by - * calling `deferred.promise`. - * - * The purpose of the promise object is to allow for interested parties to get access to the result - * of the deferred task when it completes. - * - * **Methods** - * - * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved - * or rejected, `then` calls one of the success or error callbacks asynchronously as soon as the result - * is available. The callbacks are called with a single argument: the result or rejection reason. - * - * This method *returns a new promise* which is resolved or rejected via the return value of the - * `successCallback` or `errorCallback`. - * - * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` - * - * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise, - * but to do so without modifying the final value. This is useful to release resources or do some - * clean-up that needs to be done whether the promise was rejected or resolved. See the [full - * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for - * more information. - * - * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as - * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to - * make your code IE8 compatible. - * - * # Chaining promises - * - * Because calling the `then` method of a promise returns a new derived promise, it is easily possible - * to create a chain of promises: - * - *
- *   promiseB = promiseA.then(function(result) {
- *     return result + 1;
- *   });
- *
- *   // promiseB will be resolved immediately after promiseA is resolved and its value
- *   // will be the result of promiseA incremented by 1
- * 
- * - * It is possible to create chains of any length and since a promise can be resolved with another - * promise (which will defer its resolution further), it is possible to pause/defer resolution of - * the promises at any point in the chain. This makes it possible to implement powerful APIs like - * $http's response interceptors. - * - * - * # Differences between Kris Kowal's Q and $q - * - * There are three main differences: - * - * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation - * mechanism in angular, which means faster propagation of resolution or rejection into your - * models and avoiding unnecessary browser repaints, which would result in flickering UI. - * - $q promises are recognized by the templating engine in angular, which means that in templates - * you can treat promises attached to a scope as if they were the resulting values. - * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains - * all the important functionality needed for common async tasks. - * - * # Testing - * - *
- *    it('should simulate promise', inject(function($q, $rootScope) {
- *      var deferred = $q.defer();
- *      var promise = deferred.promise;
- *      var resolvedValue;
- *
- *      promise.then(function(value) { resolvedValue = value; });
- *      expect(resolvedValue).toBeUndefined();
- *
- *      // Simulate resolving of promise
- *      deferred.resolve(123);
- *      // Note that the 'then' function does not get called synchronously.
- *      // This is because we want the promise API to always be async, whether or not
- *      // it got called synchronously or asynchronously.
- *      expect(resolvedValue).toBeUndefined();
- *
- *      // Propagate promise resolution to 'then' functions using $apply().
- *      $rootScope.$apply();
- *      expect(resolvedValue).toEqual(123);
- *    });
- *  
- */ -function $QProvider() { - - this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { - return qFactory(function(callback) { - $rootScope.$evalAsync(callback); - }, $exceptionHandler); - }]; -} - - -/** - * Constructs a promise manager. - * - * @param {function(function)} nextTick Function for executing functions in the next turn. - * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for - * debugging purposes. - * @returns {object} Promise manager. - */ -function qFactory(nextTick, exceptionHandler) { - - /** - * @ngdoc - * @name ng.$q#defer - * @methodOf ng.$q - * @description - * Creates a `Deferred` object which represents a task which will finish in the future. - * - * @returns {Deferred} Returns a new instance of deferred. - */ - var defer = function() { - var pending = [], - value, deferred; - - deferred = { - - resolve: function(val) { - if (pending) { - var callbacks = pending; - pending = undefined; - value = ref(val); - - if (callbacks.length) { - nextTick(function() { - var callback; - for (var i = 0, ii = callbacks.length; i < ii; i++) { - callback = callbacks[i]; - value.then(callback[0], callback[1], callback[2]); - } - }); - } - } - }, - - - reject: function(reason) { - deferred.resolve(reject(reason)); - }, - - - notify: function(progress) { - if (pending) { - var callbacks = pending; - - if (pending.length) { - nextTick(function() { - var callback; - for (var i = 0, ii = callbacks.length; i < ii; i++) { - callback = callbacks[i]; - callback[2](progress); - } - }); - } - } - }, - - - promise: { - then: function(callback, errback, progressback) { - var result = defer(); - - var wrappedCallback = function(value) { - try { - result.resolve((callback || defaultCallback)(value)); - } catch(e) { - result.reject(e); - exceptionHandler(e); - } - }; - - var wrappedErrback = function(reason) { - try { - result.resolve((errback || defaultErrback)(reason)); - } catch(e) { - result.reject(e); - exceptionHandler(e); - } - }; - - var wrappedProgressback = function(progress) { - try { - result.notify((progressback || defaultCallback)(progress)); - } catch(e) { - exceptionHandler(e); - } - }; - - if (pending) { - pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]); - } else { - value.then(wrappedCallback, wrappedErrback, wrappedProgressback); - } - - return result.promise; - }, - - "catch": function(callback) { - return this.then(null, callback); - }, - - "finally": function(callback) { - - function makePromise(value, resolved) { - var result = defer(); - if (resolved) { - result.resolve(value); - } else { - result.reject(value); - } - return result.promise; - } - - function handleCallback(value, isResolved) { - var callbackOutput = null; - try { - callbackOutput = (callback ||defaultCallback)(); - } catch(e) { - return makePromise(e, false); - } - if (callbackOutput && callbackOutput.then) { - return callbackOutput.then(function() { - return makePromise(value, isResolved); - }, function(error) { - return makePromise(error, false); - }); - } else { - return makePromise(value, isResolved); - } - } - - return this.then(function(value) { - return handleCallback(value, true); - }, function(error) { - return handleCallback(error, false); - }); - } - } - }; - - return deferred; - }; - - - var ref = function(value) { - if (value && value.then) return value; - return { - then: function(callback) { - var result = defer(); - nextTick(function() { - result.resolve(callback(value)); - }); - return result.promise; - } - }; - }; - - - /** - * @ngdoc - * @name ng.$q#reject - * @methodOf ng.$q - * @description - * Creates a promise that is resolved as rejected with the specified `reason`. This api should be - * used to forward rejection in a chain of promises. If you are dealing with the last promise in - * a promise chain, you don't need to worry about it. - * - * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of - * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via - * a promise error callback and you want to forward the error to the promise derived from the - * current promise, you have to "rethrow" the error by returning a rejection constructed via - * `reject`. - * - *
-   *   promiseB = promiseA.then(function(result) {
-   *     // success: do something and resolve promiseB
-   *     //          with the old or a new result
-   *     return result;
-   *   }, function(reason) {
-   *     // error: handle the error if possible and
-   *     //        resolve promiseB with newPromiseOrValue,
-   *     //        otherwise forward the rejection to promiseB
-   *     if (canHandle(reason)) {
-   *      // handle the error and recover
-   *      return newPromiseOrValue;
-   *     }
-   *     return $q.reject(reason);
-   *   });
-   * 
- * - * @param {*} reason Constant, message, exception or an object representing the rejection reason. - * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. - */ - var reject = function(reason) { - return { - then: function(callback, errback) { - var result = defer(); - nextTick(function() { - result.resolve((errback || defaultErrback)(reason)); - }); - return result.promise; - } - }; - }; - - - /** - * @ngdoc - * @name ng.$q#when - * @methodOf ng.$q - * @description - * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. - * This is useful when you are dealing with an object that might or might not be a promise, or if - * the promise comes from a source that can't be trusted. - * - * @param {*} value Value or a promise - * @returns {Promise} Returns a promise of the passed value or promise - */ - var when = function(value, callback, errback, progressback) { - var result = defer(), - done; - - var wrappedCallback = function(value) { - try { - return (callback || defaultCallback)(value); - } catch (e) { - exceptionHandler(e); - return reject(e); - } - }; - - var wrappedErrback = function(reason) { - try { - return (errback || defaultErrback)(reason); - } catch (e) { - exceptionHandler(e); - return reject(e); - } - }; - - var wrappedProgressback = function(progress) { - try { - return (progressback || defaultCallback)(progress); - } catch (e) { - exceptionHandler(e); - } - }; - - nextTick(function() { - ref(value).then(function(value) { - if (done) return; - done = true; - result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback)); - }, function(reason) { - if (done) return; - done = true; - result.resolve(wrappedErrback(reason)); - }, function(progress) { - if (done) return; - result.notify(wrappedProgressback(progress)); - }); - }); - - return result.promise; - }; - - - function defaultCallback(value) { - return value; - } - - - function defaultErrback(reason) { - return reject(reason); - } - - - /** - * @ngdoc - * @name ng.$q#all - * @methodOf ng.$q - * @description - * Combines multiple promises into a single promise that is resolved when all of the input - * promises are resolved. - * - * @param {Array.|Object.} promises An array or hash of promises. - * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, - * each value corresponding to the promise at the same index/key in the `promises` array/hash. If any of - * the promises is resolved with a rejection, this resulting promise will be resolved with the - * same rejection. - */ - function all(promises) { - var deferred = defer(), - counter = 0, - results = isArray(promises) ? [] : {}; - - forEach(promises, function(promise, key) { - counter++; - ref(promise).then(function(value) { - if (results.hasOwnProperty(key)) return; - results[key] = value; - if (!(--counter)) deferred.resolve(results); - }, function(reason) { - if (results.hasOwnProperty(key)) return; - deferred.reject(reason); - }); - }); - - if (counter === 0) { - deferred.resolve(results); - } - - return deferred.promise; - } - - return { - defer: defer, - reject: reject, - when: when, - all: all - }; -} - -/** - * DESIGN NOTES - * - * The design decisions behind the scope are heavily favored for speed and memory consumption. - * - * The typical use of scope is to watch the expressions, which most of the time return the same - * value as last time so we optimize the operation. - * - * Closures construction is expensive in terms of speed as well as memory: - * - No closures, instead use prototypical inheritance for API - * - Internal state needs to be stored on scope directly, which means that private state is - * exposed as $$____ properties - * - * Loop operations are optimized by using while(count--) { ... } - * - this means that in order to keep the same order of execution as addition we have to add - * items to the array at the beginning (shift) instead of at the end (push) - * - * Child scopes are created and removed often - * - Using an array would be slow since inserts in middle are expensive so we use linked list - * - * There are few watches then a lot of observers. This is why you don't want the observer to be - * implemented in the same way as watch. Watch requires return of initialization function which - * are expensive to construct. - */ - - -/** - * @ngdoc object - * @name ng.$rootScopeProvider - * @description - * - * Provider for the $rootScope service. - */ - -/** - * @ngdoc function - * @name ng.$rootScopeProvider#digestTtl - * @methodOf ng.$rootScopeProvider - * @description - * - * Sets the number of digest iterations the scope should attempt to execute before giving up and - * assuming that the model is unstable. - * - * The current default is 10 iterations. - * - * @param {number} limit The number of digest iterations. - */ - - -/** - * @ngdoc object - * @name ng.$rootScope - * @description - * - * Every application has a single root {@link ng.$rootScope.Scope scope}. - * All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide - * event processing life-cycle. See {@link guide/scope developer guide on scopes}. - */ -function $RootScopeProvider(){ - var TTL = 10; - var $rootScopeMinErr = minErr('$rootScope'); - - this.digestTtl = function(value) { - if (arguments.length) { - TTL = value; - } - return TTL; - }; - - this.$get = ['$injector', '$exceptionHandler', '$parse', - function( $injector, $exceptionHandler, $parse) { - - /** - * @ngdoc function - * @name ng.$rootScope.Scope - * - * @description - * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the - * {@link AUTO.$injector $injector}. Child scopes are created using the - * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when - * compiled HTML template is executed.) - * - * Here is a simple scope snippet to show how you can interact with the scope. - *
-     * 
-     * 
- * - * # Inheritance - * A scope can inherit from a parent scope, as in this example: - *
-         var parent = $rootScope;
-         var child = parent.$new();
-
-         parent.salutation = "Hello";
-         child.name = "World";
-         expect(child.salutation).toEqual('Hello');
-
-         child.salutation = "Welcome";
-         expect(child.salutation).toEqual('Welcome');
-         expect(parent.salutation).toEqual('Hello');
-     * 
- * - * - * @param {Object.=} providers Map of service factory which need to be provided - * for the current scope. Defaults to {@link ng}. - * @param {Object.=} instanceCache Provides pre-instantiated services which should - * append/override services provided by `providers`. This is handy when unit-testing and having - * the need to override a default service. - * @returns {Object} Newly created scope. - * - */ - function Scope() { - this.$id = nextUid(); - this.$$phase = this.$parent = this.$$watchers = - this.$$nextSibling = this.$$prevSibling = - this.$$childHead = this.$$childTail = null; - this['this'] = this.$root = this; - this.$$destroyed = false; - this.$$asyncQueue = []; - this.$$listeners = {}; - this.$$isolateBindings = {}; - } - - /** - * @ngdoc property - * @name ng.$rootScope.Scope#$id - * @propertyOf ng.$rootScope.Scope - * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for - * debugging. - */ - - - Scope.prototype = { - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$new - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Creates a new child {@link ng.$rootScope.Scope scope}. - * - * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and - * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope - * hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. - * - * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for - * the scope and its child scopes to be permanently detached from the parent and thus stop - * participating in model change detection and listener notification by invoking. - * - * @param {boolean} isolate if true then the scope does not prototypically inherit from the - * parent scope. The scope is isolated, as it can not see parent scope properties. - * When creating widgets it is useful for the widget to not accidentally read parent - * state. - * - * @returns {Object} The newly created child scope. - * - */ - $new: function(isolate) { - var Child, - child; - - if (isolate) { - child = new Scope(); - child.$root = this.$root; - // ensure that there is just one async queue per $rootScope and it's children - child.$$asyncQueue = this.$$asyncQueue; - } else { - Child = function() {}; // should be anonymous; This is so that when the minifier munges - // the name it does not become random set of chars. These will then show up as class - // name in the debugger. - Child.prototype = this; - child = new Child(); - child.$id = nextUid(); - } - child['this'] = child; - child.$$listeners = {}; - child.$parent = this; - child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; - child.$$prevSibling = this.$$childTail; - if (this.$$childHead) { - this.$$childTail.$$nextSibling = child; - this.$$childTail = child; - } else { - this.$$childHead = this.$$childTail = child; - } - return child; - }, - - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$watch - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Registers a `listener` callback to be executed whenever the `watchExpression` changes. - * - * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and - * should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()} - * reruns when it detects changes the `watchExpression` can execute multiple times per - * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) - * - The `listener` is called only when the value from the current `watchExpression` and the - * previous call to `watchExpression` are not equal (with the exception of the initial run, - * see below). The inequality is determined according to - * {@link angular.equals} function. To save the value of the object for later comparison, the - * {@link angular.copy} function is used. It also means that watching complex options will - * have adverse memory and performance implications. - * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This - * is achieved by rerunning the watchers until no changes are detected. The rerun iteration - * limit is 10 to prevent an infinite loop deadlock. - * - * - * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, - * you can register a `watchExpression` function with no `listener`. (Since `watchExpression` - * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is - * detected, be prepared for multiple calls to your listener.) - * - * After a watcher is registered with the scope, the `listener` fn is called asynchronously - * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the - * watcher. In rare cases, this is undesirable because the listener is called when the result - * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you - * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the - * listener was called due to initialization. - * - * - * # Example - *
-           // let's assume that scope was dependency injected as the $rootScope
-           var scope = $rootScope;
-           scope.name = 'misko';
-           scope.counter = 0;
-
-           expect(scope.counter).toEqual(0);
-           scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; });
-           expect(scope.counter).toEqual(0);
-
-           scope.$digest();
-           // no variable change
-           expect(scope.counter).toEqual(0);
-
-           scope.name = 'adam';
-           scope.$digest();
-           expect(scope.counter).toEqual(1);
-       * 
- * - * - * - * @param {(function()|string)} watchExpression Expression that is evaluated on each - * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a - * call to the `listener`. - * - * - `string`: Evaluated as {@link guide/expression expression} - * - `function(scope)`: called with current `scope` as a parameter. - * @param {(function()|string)=} listener Callback called whenever the return value of - * the `watchExpression` changes. - * - * - `string`: Evaluated as {@link guide/expression expression} - * - `function(newValue, oldValue, scope)`: called with current and previous values as parameters. - * - * @param {boolean=} objectEquality Compare object for equality rather than for reference. - * @returns {function()} Returns a deregistration function for this listener. - */ - $watch: function(watchExp, listener, objectEquality) { - var scope = this, - get = compileToFn(watchExp, 'watch'), - array = scope.$$watchers, - watcher = { - fn: listener, - last: initWatchVal, - get: get, - exp: watchExp, - eq: !!objectEquality - }; - - // in the case user pass string, we need to compile it, do we really need this ? - if (!isFunction(listener)) { - var listenFn = compileToFn(listener || noop, 'listener'); - watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; - } - - if (typeof watchExp == 'string' && get.constant) { - var originalFn = watcher.fn; - watcher.fn = function(newVal, oldVal, scope) { - originalFn.call(this, newVal, oldVal, scope); - arrayRemove(array, watcher); - }; - } - - if (!array) { - array = scope.$$watchers = []; - } - // we use unshift since we use a while loop in $digest for speed. - // the while loop reads in reverse order. - array.unshift(watcher); - - return function() { - arrayRemove(array, watcher); - }; - }, - - - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$watchCollection - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Shallow watches the properties of an object and fires whenever any of the properties change - * (for arrays this implies watching the array items, for object maps this implies watching the properties). - * If a change is detected the `listener` callback is fired. - * - * - The `obj` collection is observed via standard $watch operation and is examined on every call to $digest() to - * see if any items have been added, removed, or moved. - * - The `listener` is called whenever anything within the `obj` has changed. Examples include adding new items - * into the object or array, removing and moving items around. - * - * - * # Example - *
-          $scope.names = ['igor', 'matias', 'misko', 'james'];
-          $scope.dataCount = 4;
-
-          $scope.$watchCollection('names', function(newNames, oldNames) {
-            $scope.dataCount = newNames.length;
-          });
-
-          expect($scope.dataCount).toEqual(4);
-          $scope.$digest();
-
-          //still at 4 ... no changes
-          expect($scope.dataCount).toEqual(4);
-
-          $scope.names.pop();
-          $scope.$digest();
-
-          //now there's been a change
-          expect($scope.dataCount).toEqual(3);
-       * 
- * - * - * @param {string|Function(scope)} obj Evaluated as {@link guide/expression expression}. The expression value - * should evaluate to an object or an array which is observed on each - * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the collection will trigger - * a call to the `listener`. - * - * @param {function(newCollection, oldCollection, scope)} listener a callback function that is fired with both - * the `newCollection` and `oldCollection` as parameters. - * The `newCollection` object is the newly modified data obtained from the `obj` expression and the - * `oldCollection` object is a copy of the former collection data. - * The `scope` refers to the current scope. - * - * @returns {function()} Returns a de-registration function for this listener. When the de-registration function is executed - * then the internal watch operation is terminated. - */ - $watchCollection: function(obj, listener) { - var self = this; - var oldValue; - var newValue; - var changeDetected = 0; - var objGetter = $parse(obj); - var internalArray = []; - var internalObject = {}; - var oldLength = 0; - - function $watchCollectionWatch() { - newValue = objGetter(self); - var newLength, key; - - if (!isObject(newValue)) { - if (oldValue !== newValue) { - oldValue = newValue; - changeDetected++; - } - } else if (isArrayLike(newValue)) { - if (oldValue !== internalArray) { - // we are transitioning from something which was not an array into array. - oldValue = internalArray; - oldLength = oldValue.length = 0; - changeDetected++; - } - - newLength = newValue.length; - - if (oldLength !== newLength) { - // if lengths do not match we need to trigger change notification - changeDetected++; - oldValue.length = oldLength = newLength; - } - // copy the items to oldValue and look for changes. - for (var i = 0; i < newLength; i++) { - if (oldValue[i] !== newValue[i]) { - changeDetected++; - oldValue[i] = newValue[i]; - } - } - } else { - if (oldValue !== internalObject) { - // we are transitioning from something which was not an object into object. - oldValue = internalObject = {}; - oldLength = 0; - changeDetected++; - } - // copy the items to oldValue and look for changes. - newLength = 0; - for (key in newValue) { - if (newValue.hasOwnProperty(key)) { - newLength++; - if (oldValue.hasOwnProperty(key)) { - if (oldValue[key] !== newValue[key]) { - changeDetected++; - oldValue[key] = newValue[key]; - } - } else { - oldLength++; - oldValue[key] = newValue[key]; - changeDetected++; - } - } - } - if (oldLength > newLength) { - // we used to have more keys, need to find them and destroy them. - changeDetected++; - for(key in oldValue) { - if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) { - oldLength--; - delete oldValue[key]; - } - } - } - } - return changeDetected; - } - - function $watchCollectionAction() { - listener(newValue, oldValue, self); - } - - return this.$watch($watchCollectionWatch, $watchCollectionAction); - }, - - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$digest - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children. - * Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the - * `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are - * firing. This means that it is possible to get into an infinite loop. This function will throw - * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10. - * - * Usually you don't call `$digest()` directly in - * {@link ng.directive:ngController controllers} or in - * {@link ng.$compileProvider#directive directives}. - * Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a - * {@link ng.$compileProvider#directive directives}) will force a `$digest()`. - * - * If you want to be notified whenever `$digest()` is called, - * you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()} - * with no `listener`. - * - * You may have a need to call `$digest()` from within unit-tests, to simulate the scope - * life-cycle. - * - * # Example - *
-           var scope = ...;
-           scope.name = 'misko';
-           scope.counter = 0;
-
-           expect(scope.counter).toEqual(0);
-           scope.$watch('name', function(newValue, oldValue) {
-             scope.counter = scope.counter + 1;
-           });
-           expect(scope.counter).toEqual(0);
-
-           scope.$digest();
-           // no variable change
-           expect(scope.counter).toEqual(0);
-
-           scope.name = 'adam';
-           scope.$digest();
-           expect(scope.counter).toEqual(1);
-       * 
- * - */ - $digest: function() { - var watch, value, last, - watchers, - asyncQueue = this.$$asyncQueue, - length, - dirty, ttl = TTL, - next, current, target = this, - watchLog = [], - logIdx, logMsg; - - beginPhase('$digest'); - - do { // "while dirty" loop - dirty = false; - current = target; - - while(asyncQueue.length) { - try { - current.$eval(asyncQueue.shift()); - } catch (e) { - $exceptionHandler(e); - } - } - - do { // "traverse the scopes" loop - if ((watchers = current.$$watchers)) { - // process our watches - length = watchers.length; - while (length--) { - try { - watch = watchers[length]; - // Most common watches are on primitives, in which case we can short - // circuit it with === operator, only when === fails do we use .equals - if (watch && (value = watch.get(current)) !== (last = watch.last) && - !(watch.eq - ? equals(value, last) - : (typeof value == 'number' && typeof last == 'number' - && isNaN(value) && isNaN(last)))) { - dirty = true; - watch.last = watch.eq ? copy(value) : value; - watch.fn(value, ((last === initWatchVal) ? value : last), current); - if (ttl < 5) { - logIdx = 4 - ttl; - if (!watchLog[logIdx]) watchLog[logIdx] = []; - logMsg = (isFunction(watch.exp)) - ? 'fn: ' + (watch.exp.name || watch.exp.toString()) - : watch.exp; - logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); - watchLog[logIdx].push(logMsg); - } - } - } catch (e) { - $exceptionHandler(e); - } - } - } - - // Insanity Warning: scope depth-first traversal - // yes, this code is a bit crazy, but it works and we have tests to prove it! - // this piece should be kept in sync with the traversal in $broadcast - if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { - while(current !== target && !(next = current.$$nextSibling)) { - current = current.$parent; - } - } - } while ((current = next)); - - if(dirty && !(ttl--)) { - clearPhase(); - throw $rootScopeMinErr('infdig', - '{0} $digest() iterations reached. Aborting!\nWatchers fired in the last 5 iterations: {1}', - TTL, toJson(watchLog)); - } - } while (dirty || asyncQueue.length); - - clearPhase(); - }, - - - /** - * @ngdoc event - * @name ng.$rootScope.Scope#$destroy - * @eventOf ng.$rootScope.Scope - * @eventType broadcast on scope being destroyed - * - * @description - * Broadcasted when a scope and its children are being destroyed. - * - * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to - * clean up DOM bindings before an element is removed from the DOM. - */ - - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$destroy - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Removes the current scope (and all of its children) from the parent scope. Removal implies - * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer - * propagate to the current scope and its children. Removal also implies that the current - * scope is eligible for garbage collection. - * - * The `$destroy()` is usually used by directives such as - * {@link ng.directive:ngRepeat ngRepeat} for managing the - * unrolling of the loop. - * - * Just before a scope is destroyed a `$destroy` event is broadcasted on this scope. - * Application code can register a `$destroy` event handler that will give it chance to - * perform any necessary cleanup. - * - * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to - * clean up DOM bindings before an element is removed from the DOM. - */ - $destroy: function() { - // we can't destroy the root scope or a scope that has been already destroyed - if ($rootScope == this || this.$$destroyed) return; - var parent = this.$parent; - - this.$broadcast('$destroy'); - this.$$destroyed = true; - - if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; - if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; - if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; - if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; - - // This is bogus code that works around Chrome's GC leak - // see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 - this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = - this.$$childTail = null; - }, - - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$eval - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Executes the `expression` on the current scope returning the result. Any exceptions in the - * expression are propagated (uncaught). This is useful when evaluating Angular expressions. - * - * # Example - *
-           var scope = ng.$rootScope.Scope();
-           scope.a = 1;
-           scope.b = 2;
-
-           expect(scope.$eval('a+b')).toEqual(3);
-           expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
-       * 
- * - * @param {(string|function())=} expression An angular expression to be executed. - * - * - `string`: execute using the rules as defined in {@link guide/expression expression}. - * - `function(scope)`: execute the function with the current `scope` parameter. - * - * @returns {*} The result of evaluating the expression. - */ - $eval: function(expr, locals) { - return $parse(expr)(this, locals); - }, - - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$evalAsync - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Executes the expression on the current scope at a later point in time. - * - * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that: - * - * - it will execute in the current script execution context (before any DOM rendering). - * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after - * `expression` execution. - * - * Any exceptions from the execution of the expression are forwarded to the - * {@link ng.$exceptionHandler $exceptionHandler} service. - * - * @param {(string|function())=} expression An angular expression to be executed. - * - * - `string`: execute using the rules as defined in {@link guide/expression expression}. - * - `function(scope)`: execute the function with the current `scope` parameter. - * - */ - $evalAsync: function(expr) { - this.$$asyncQueue.push(expr); - }, - - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$apply - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * `$apply()` is used to execute an expression in angular from outside of the angular framework. - * (For example from browser DOM events, setTimeout, XHR or third party libraries). - * Because we are calling into the angular framework we need to perform proper scope life-cycle - * of {@link ng.$exceptionHandler exception handling}, - * {@link ng.$rootScope.Scope#$digest executing watches}. - * - * ## Life cycle - * - * # Pseudo-Code of `$apply()` - *
-           function $apply(expr) {
-             try {
-               return $eval(expr);
-             } catch (e) {
-               $exceptionHandler(e);
-             } finally {
-               $root.$digest();
-             }
-           }
-       * 
- * - * - * Scope's `$apply()` method transitions through the following stages: - * - * 1. The {@link guide/expression expression} is executed using the - * {@link ng.$rootScope.Scope#$eval $eval()} method. - * 2. Any exceptions from the execution of the expression are forwarded to the - * {@link ng.$exceptionHandler $exceptionHandler} service. - * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression - * was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. - * - * - * @param {(string|function())=} exp An angular expression to be executed. - * - * - `string`: execute using the rules as defined in {@link guide/expression expression}. - * - `function(scope)`: execute the function with current `scope` parameter. - * - * @returns {*} The result of evaluating the expression. - */ - $apply: function(expr) { - try { - beginPhase('$apply'); - return this.$eval(expr); - } catch (e) { - $exceptionHandler(e); - } finally { - clearPhase(); - try { - $rootScope.$digest(); - } catch (e) { - $exceptionHandler(e); - throw e; - } - } - }, - - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$on - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of - * event life cycle. - * - * The event listener function format is: `function(event, args...)`. The `event` object - * passed into the listener has the following attributes: - * - * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or `$broadcast`-ed. - * - `currentScope` - `{Scope}`: the current scope which is handling the event. - * - `name` - `{string}`: Name of the event. - * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel further event - * propagation (available only for events that were `$emit`-ed). - * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag to true. - * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. - * - * @param {string} name Event name to listen on. - * @param {function(event, args...)} listener Function to call when the event is emitted. - * @returns {function()} Returns a deregistration function for this listener. - */ - $on: function(name, listener) { - var namedListeners = this.$$listeners[name]; - if (!namedListeners) { - this.$$listeners[name] = namedListeners = []; - } - namedListeners.push(listener); - - return function() { - namedListeners[indexOf(namedListeners, listener)] = null; - }; - }, - - - /** - * @ngdoc function - * @name ng.$rootScope.Scope#$emit - * @methodOf ng.$rootScope.Scope - * @function - * - * @description - * Dispatches an event `name` upwards through the scope hierarchy notifying the - * registered {@link ng.$rootScope.Scope#$on} listeners. - * - * The event life cycle starts at the scope on which `$emit` was called. All - * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. - * Afterwards, the event traverses upwards toward the root scope and calls all registered - * listeners along the way. The event will stop propagating if one of the listeners cancels it. - * - * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed - * onto the {@link ng.$exceptionHandler $exceptionHandler} service. - * - * @param {string} name Event name to emit. - * @param {...*} args Optional set of arguments which will be passed onto the event listeners. - * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} - */ - $emit: function(name, args) { - var empty = [], - namedListeners, - scope = this, - stopPropagation = false, - event = { - name: name, - targetScope: scope, - stopPropagation: function() {stopPropagation = true;}, - preventDefault: function() { - event.defaultPrevented = true; - }, - defaultPrevented: false - }, - listenerArgs = concat([event], arguments, 1), - i, length; - - do { - namedListeners = scope.$$listeners[name] || empty; - event.currentScope = scope; - for (i=0, length=namedListeners.length; i to learn more about them. - * You can ensure your document is in standards mode and not quirks mode by adding `` - * to the top of your HTML document. - * - * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for - * security vulnerabilities such as XSS, clickjacking, etc. a lot easier. - * - * Here's an example of a binding in a privileged context: - * - *
- *     
- *     
- *
- * - * Notice that `ng-bind-html` is bound to `{{userHtml}}` controlled by the user. With SCE - * disabled, this application allows the user to render arbitrary HTML into the DIV. - * In a more realistic example, one may be rendering user comments, blog articles, etc. via - * bindings. (HTML is just one example of a context where rendering user controlled input creates - * security vulnerabilities.) - * - * For the case of HTML, you might use a library, either on the client side, or on the server side, - * to sanitize unsafe HTML before binding to the value and rendering it in the document. - * - * How would you ensure that every place that used these types of bindings was bound to a value that - * was sanitized by your library (or returned as safe for rendering by your server?) How can you - * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some - * properties/fields and forgot to update the binding to the sanitized value? - * - * To be secure by default, you want to ensure that any such bindings are disallowed unless you can - * determine that something explicitly says it's safe to use a value for binding in that - * context. You can then audit your code (a simple grep would do) to ensure that this is only done - * for those values that you can easily tell are safe - because they were received from your server, - * sanitized by your library, etc. You can organize your codebase to help with this - perhaps - * allowing only the files in a specific directory to do this. Ensuring that the internal API - * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task. - * - * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs} (and shorthand - * methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to obtain values that will be - * accepted by SCE / privileged contexts. - * - * - * ## How does it work? - * - * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted - * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link - * ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the - * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. - * - * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link - * ng.$sce#parseHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly - * simplified): - * - *
- *   var ngBindHtmlDirective = ['$sce', function($sce) {
- *     return function(scope, element, attr) {
- *       scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
- *         element.html(value || '');
- *       });
- *     };
- *   }];
- * 
- * - * ## Impact on loading templates - * - * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as - * `templateUrl`'s specified by {@link guide/directive directives}. - * - * By default, Angular only loads templates from the same domain and protocol as the application - * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl - * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or - * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist - * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. - * - * *Please note*: - * The browser's - * {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest - * Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing (CORS)} - * policy apply in addition to this and may further restrict whether the template is successfully - * loaded. This means that without the right CORS policy, loading templates from a different domain - * won't work on all browsers. Also, loading templates from `file://` URL does not work on some - * browsers. - * - * ## This feels like too much overhead for the developer? - * - * It's important to remember that SCE only applies to interpolation expressions. - * - * If your expressions are constant literals, they're automatically trusted and you don't need to - * call `$sce.trustAs` on them. (e.g. - * `
`) just works. - * - * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them - * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here. - * - * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load - * templates in `ng-include` from your application's domain without having to even know about SCE. - * It blocks loading templates from other domains or loading templates over http from an https - * served document. You can change these by setting your own custom {@link - * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link - * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs. - * - * This significantly reduces the overhead. It is far easier to pay the small overhead and have an - * application that's secure and can be audited to verify that with much more ease than bolting - * security onto an application later. - * - * ## What trusted context types are supported? - * - * | Context | Notes | - * |=====================|================| - * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. | - * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. | - * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`
Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. | - * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. | - * - * ## Show me an example. - * - * - * - * @example - - -
-

- User comments
- By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when $sanitize is available. If $sanitize isn't available, this results in an error instead of an exploit. -
-
- {{userComment.name}}: - -
-
-
-
-
- - - var mySceApp = angular.module('mySceApp', ['ngSanitize']); - - mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) { - var self = this; - $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) { - self.userComments = userComments; - }); - self.explicitlyTrustedHtml = $sce.trustAsHtml( - 'Hover over this text.'); - }); - - - - [ - { "name": "Alice", - "htmlComment": "Is anyone reading this?" - }, - { "name": "Bob", - "htmlComment": "Yes! Am I the only other one?" - } - ] - - - - describe('SCE doc demo', function() { - it('should sanitize untrusted values', function() { - expect(element('.htmlComment').html()).toBe('Is anyone reading this?'); - }); - it('should NOT sanitize explicitly trusted values', function() { - expect(element('#explicitlyTrustedHtml').html()).toBe( - 'Hover over this text.'); - }); - }); - -
- * - * - * - * ## Can I disable SCE completely? - * - * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits - * for little coding overhead. It will be much harder to take an SCE disabled application and - * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE - * for cases where you have a lot of existing code that was written before SCE was introduced and - * you're migrating them a module at a time. - * - * That said, here's how you can completely disable SCE: - * - *
- *   angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
- *     // Completely disable SCE.  For demonstration purposes only!
- *     // Do not use in new projects.
- *     $sceProvider.enabled(false);
- *   });
- * 
- * - */ - -function $SceProvider() { - var enabled = true; - - /** - * @ngdoc function - * @name ng.sceProvider#enabled - * @methodOf ng.$sceProvider - * @function - * - * @param {boolean=} value If provided, then enables/disables SCE. - * @return {boolean} true if SCE is enabled, false otherwise. - * - * @description - * Enables/disables SCE and returns the current value. - */ - this.enabled = function (value) { - if (arguments.length) { - enabled = !!value; - } - return enabled; - }; - - - /* Design notes on the default implementation for SCE. - * - * The API contract for the SCE delegate - * ------------------------------------- - * The SCE delegate object must provide the following 3 methods: - * - * - trustAs(contextEnum, value) - * This method is used to tell the SCE service that the provided value is OK to use in the - * contexts specified by contextEnum. It must return an object that will be accepted by - * getTrusted() for a compatible contextEnum and return this value. - * - * - valueOf(value) - * For values that were not produced by trustAs(), return them as is. For values that were - * produced by trustAs(), return the corresponding input value to trustAs. Basically, if - * trustAs is wrapping the given values into some type, this operation unwraps it when given - * such a value. - * - * - getTrusted(contextEnum, value) - * This function should return the a value that is safe to use in the context specified by - * contextEnum or throw and exception otherwise. - * - * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be opaque - * or wrapped in some holder object. That happens to be an implementation detail. For instance, - * an implementation could maintain a registry of all trusted objects by context. In such a case, - * trustAs() would return the same object that was passed in. getTrusted() would return the same - * object passed in if it was found in the registry under a compatible context or throw an - * exception otherwise. An implementation might only wrap values some of the time based on - * some criteria. getTrusted() might return a value and not throw an exception for special - * constants or objects even if not wrapped. All such implementations fulfill this contract. - * - * - * A note on the inheritance model for SCE contexts - * ------------------------------------------------ - * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This - * is purely an implementation details. - * - * The contract is simply this: - * - * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value) - * will also succeed. - * - * Inheritance happens to capture this in a natural way. In some future, we - * may not use inheritance anymore. That is OK because no code outside of - * sce.js and sceSpecs.js would need to be aware of this detail. - */ - - this.$get = ['$parse', '$document', '$sceDelegate', function( - $parse, $document, $sceDelegate) { - // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows - // the "expression(javascript expression)" syntax which is insecure. - if (enabled && msie) { - var documentMode = $document[0].documentMode; - if (documentMode !== undefined && documentMode < 8) { - throw $sceMinErr('iequirks', - 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' + - 'mode. You can fix this by adding the text to the top of your HTML ' + - 'document. See http://docs.angularjs.org/api/ng.$sce for more information.'); - } - } - - var sce = copy(SCE_CONTEXTS); - - /** - * @ngdoc function - * @name ng.sce#isEnabled - * @methodOf ng.$sce - * @function - * - * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you - * have to do it at module config time on {@link ng.$sceProvider $sceProvider}. - * - * @description - * Returns a boolean indicating if SCE is enabled. - */ - sce.isEnabled = function () { - return enabled; - }; - sce.trustAs = $sceDelegate.trustAs; - sce.getTrusted = $sceDelegate.getTrusted; - sce.valueOf = $sceDelegate.valueOf; - - if (!enabled) { - sce.trustAs = sce.getTrusted = function(type, value) { return value; }, - sce.valueOf = identity - } - - /** - * @ngdoc method - * @name ng.$sce#parse - * @methodOf ng.$sce - * - * @description - * Converts Angular {@link guide/expression expression} into a function. This is like {@link - * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it - * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*, - * *result*)} - * - * @param {string} type The kind of SCE context in which this result will be used. - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ - sce.parseAs = function sceParseAs(type, expr) { - var parsed = $parse(expr); - if (parsed.literal && parsed.constant) { - return parsed; - } else { - return function sceParseAsTrusted(self, locals) { - return sce.getTrusted(type, parsed(self, locals)); - } - } - }; - - /** - * @ngdoc method - * @name ng.$sce#trustAs - * @methodOf ng.$sce - * - * @description - * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, returns an object - * that is trusted by angular for use in specified strict contextual escaping contexts (such as - * ng-html-bind-unsafe, ng-include, any src attribute interpolation, any dom event binding - * attribute interpolation such as for onclick, etc.) that uses the provided value. See * - * {@link ng.$sce $sce} for enabling strict contextual escaping. - * - * @param {string} type The kind of context in which this value is safe for use. e.g. url, - * resource_url, html, js and css. - * @param {*} value The value that that should be considered trusted/safe. - * @returns {*} A value that can be used to stand in for the provided `value` in places - * where Angular expects a $sce.trustAs() return value. - */ - - /** - * @ngdoc method - * @name ng.$sce#trustAsHtml - * @methodOf ng.$sce - * - * @description - * Shorthand method. `$sce.trustAsHtml(value)` → {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`} - * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml - * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the - * return value of {@link ng.$sce#trustAs $sce.trustAs}.) - */ - - /** - * @ngdoc method - * @name ng.$sce#trustAsUrl - * @methodOf ng.$sce - * - * @description - * Shorthand method. `$sce.trustAsUrl(value)` → {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`} - * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl - * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the - * return value of {@link ng.$sce#trustAs $sce.trustAs}.) - */ - - /** - * @ngdoc method - * @name ng.$sce#trustAsResourceUrl - * @methodOf ng.$sce - * - * @description - * Shorthand method. `$sce.trustAsResourceUrl(value)` → {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} - * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl - * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the return - * value of {@link ng.$sce#trustAs $sce.trustAs}.) - */ - - /** - * @ngdoc method - * @name ng.$sce#trustAsJs - * @methodOf ng.$sce - * - * @description - * Shorthand method. `$sce.trustAsJs(value)` → {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`} - * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs - * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the - * return value of {@link ng.$sce#trustAs $sce.trustAs}.) - */ - - /** - * @ngdoc method - * @name ng.$sce#getTrusted - * @methodOf ng.$sce - * - * @description - * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, takes - * the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the originally supplied - * value if the queried context type is a supertype of the created type. If this condition - * isn't satisfied, throws an exception. - * - * @param {string} type The kind of context in which this value is to be used. - * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`} call. - * @returns {*} The value the was originally provided to {@link ng.$sce#trustAs `$sce.trustAs`} if - * valid in this context. Otherwise, throws an exception. - */ - - /** - * @ngdoc method - * @name ng.$sce#getTrustedHtml - * @methodOf ng.$sce - * - * @description - * Shorthand method. `$sce.getTrustedHtml(value)` → {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} - * - * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)` - */ - - /** - * @ngdoc method - * @name ng.$sce#getTrustedCss - * @methodOf ng.$sce - * - * @description - * Shorthand method. `$sce.getTrustedCss(value)` → {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} - * - * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)` - */ - - /** - * @ngdoc method - * @name ng.$sce#getTrustedUrl - * @methodOf ng.$sce - * - * @description - * Shorthand method. `$sce.getTrustedUrl(value)` → {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} - * - * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)` - */ - - /** - * @ngdoc method - * @name ng.$sce#getTrustedResourceUrl - * @methodOf ng.$sce - * - * @description - * Shorthand method. `$sce.getTrustedResourceUrl(value)` → {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} - * - * @param {*} value The value to pass to `$sceDelegate.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` - */ - - /** - * @ngdoc method - * @name ng.$sce#getTrustedJs - * @methodOf ng.$sce - * - * @description - * Shorthand method. `$sce.getTrustedJs(value)` → {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} - * - * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)` - */ - - /** - * @ngdoc method - * @name ng.$sce#parseAsHtml - * @methodOf ng.$sce - * - * @description - * Shorthand method. `$sce.parseAsHtml(expression string)` → {@link ng.$sce#parse `$sce.parseAs($sce.HTML, value)`} - * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ - - /** - * @ngdoc method - * @name ng.$sce#parseAsCss - * @methodOf ng.$sce - * - * @description - * Shorthand method. `$sce.parseAsCss(value)` → {@link ng.$sce#parse `$sce.parseAs($sce.CSS, value)`} - * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ - - /** - * @ngdoc method - * @name ng.$sce#parseAsUrl - * @methodOf ng.$sce - * - * @description - * Shorthand method. `$sce.parseAsUrl(value)` → {@link ng.$sce#parse `$sce.parseAs($sce.URL, value)`} - * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ - - /** - * @ngdoc method - * @name ng.$sce#parseAsResourceUrl - * @methodOf ng.$sce - * - * @description - * Shorthand method. `$sce.parseAsResourceUrl(value)` → {@link ng.$sce#parse `$sce.parseAs($sce.RESOURCE_URL, value)`} - * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ - - /** - * @ngdoc method - * @name ng.$sce#parseAsJs - * @methodOf ng.$sce - * - * @description - * Shorthand method. `$sce.parseAsJs(value)` → {@link ng.$sce#parse `$sce.parseAs($sce.JS, value)`} - * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ - - // Shorthand delegations. - var parse = sce.parseAs, - getTrusted = sce.getTrusted, - trustAs = sce.trustAs; - - angular.forEach(SCE_CONTEXTS, function (enumValue, name) { - var lName = lowercase(name); - sce[camelCase("parse_as_" + lName)] = function (expr) { - return parse(enumValue, expr); - } - sce[camelCase("get_trusted_" + lName)] = function (value) { - return getTrusted(enumValue, value); - } - sce[camelCase("trust_as_" + lName)] = function (value) { - return trustAs(enumValue, value); - } - }); - - return sce; - }]; -} - -/** - * !!! This is an undocumented "private" service !!! - * - * @name ng.$sniffer - * @requires $window - * @requires $document - * - * @property {boolean} history Does the browser support html5 history api ? - * @property {boolean} hashchange Does the browser support hashchange event ? - * @property {boolean} transitions Does the browser support CSS transition events ? - * @property {boolean} animations Does the browser support CSS animation events ? - * - * @description - * This is very simple implementation of testing browser's features. - */ -function $SnifferProvider() { - this.$get = ['$window', '$document', function($window, $document) { - var eventSupport = {}, - android = int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), - document = $document[0] || {}, - vendorPrefix, - vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/, - bodyStyle = document.body && document.body.style, - transitions = false, - animations = false, - match; - - if (bodyStyle) { - for(var prop in bodyStyle) { - if(match = vendorRegex.exec(prop)) { - vendorPrefix = match[0]; - vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1); - break; - } - } - transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle)); - animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle)); - - if (android && (!transitions||!animations)) { - transitions = isString(document.body.style.webkitTransition); - animations = isString(document.body.style.webkitAnimation); - } - } - - - return { - // Android has history.pushState, but it does not update location correctly - // so let's not use the history API at all. - // http://code.google.com/p/android/issues/detail?id=17471 - // https://github.com/angular/angular.js/issues/904 - history: !!($window.history && $window.history.pushState && !(android < 4)), - hashchange: 'onhashchange' in $window && - // IE8 compatible mode lies - (!document.documentMode || document.documentMode > 7), - hasEvent: function(event) { - // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have - // it. In particular the event is not fired when backspace or delete key are pressed or - // when cut operation is performed. - if (event == 'input' && msie == 9) return false; - - if (isUndefined(eventSupport[event])) { - var divElm = document.createElement('div'); - eventSupport[event] = 'on' + event in divElm; - } - - return eventSupport[event]; - }, - csp: document.securityPolicy ? document.securityPolicy.isActive : false, - vendorPrefix: vendorPrefix, - transitions : transitions, - animations : animations - }; - }]; -} - -function $TimeoutProvider() { - this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler', - function($rootScope, $browser, $q, $exceptionHandler) { - var deferreds = {}; - - - /** - * @ngdoc function - * @name ng.$timeout - * @requires $browser - * - * @description - * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch - * block and delegates any exceptions to - * {@link ng.$exceptionHandler $exceptionHandler} service. - * - * The return value of registering a timeout function is a promise, which will be resolved when - * the timeout is reached and the timeout function is executed. - * - * To cancel a timeout request, call `$timeout.cancel(promise)`. - * - * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to - * synchronously flush the queue of deferred functions. - * - * @param {function()} fn A function, whose execution should be delayed. - * @param {number=} [delay=0] Delay in milliseconds. - * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise - * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. - * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this - * promise will be resolved with is the return value of the `fn` function. - */ - function timeout(fn, delay, invokeApply) { - var deferred = $q.defer(), - promise = deferred.promise, - skipApply = (isDefined(invokeApply) && !invokeApply), - timeoutId, cleanup; - - timeoutId = $browser.defer(function() { - try { - deferred.resolve(fn()); - } catch(e) { - deferred.reject(e); - $exceptionHandler(e); - } - - if (!skipApply) $rootScope.$apply(); - }, delay); - - cleanup = function() { - delete deferreds[promise.$$timeoutId]; - }; - - promise.$$timeoutId = timeoutId; - deferreds[timeoutId] = deferred; - promise.then(cleanup, cleanup); - - return promise; - } - - - /** - * @ngdoc function - * @name ng.$timeout#cancel - * @methodOf ng.$timeout - * - * @description - * Cancels a task associated with the `promise`. As a result of this, the promise will be - * resolved with a rejection. - * - * @param {Promise=} promise Promise returned by the `$timeout` function. - * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully - * canceled. - */ - timeout.cancel = function(promise) { - if (promise && promise.$$timeoutId in deferreds) { - deferreds[promise.$$timeoutId].reject('canceled'); - return $browser.defer.cancel(promise.$$timeoutId); - } - return false; - }; - - return timeout; - }]; -} - -function $$UrlUtilsProvider() { - this.$get = [function() { - var urlParsingNode = document.createElement("a"), - // NOTE: The usage of window and document instead of $window and $document here is - // deliberate. This service depends on the specific behavior of anchor nodes created by the - // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and - // cause us to break tests. In addition, when the browser resolves a URL for XHR, it - // doesn't know about mocked locations and resolves URLs to the real document - which is - // exactly the behavior needed here. There is little value is mocking these our for this - // service. - originUrl = resolve(window.location.href, true); - - /** - * @description - * Normalizes and optionally parses a URL. - * - * NOTE: This is a private service. The API is subject to change unpredictably in any commit. - * - * Implementation Notes for non-IE browsers - * ---------------------------------------- - * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, - * results both in the normalizing and parsing of the URL. Normalizing means that a relative - * URL will be resolved into an absolute URL in the context of the application document. - * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related - * properties are all populated to reflect the normalized URL. This approach has wide - * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See - * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html - * - * Implementation Notes for IE - * --------------------------- - * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other - * browsers. However, the parsed components will not be set if the URL assigned did not specify - * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We - * work around that by performing the parsing in a 2nd step by taking a previously normalized - * URL (e.g. by assining to a.href) and assigning it a.href again. This correctly populates the - * properties such as protocol, hostname, port, etc. - * - * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one - * uses the inner HTML approach to assign the URL as part of an HTML snippet - - * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL. - * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception. - * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that - * method and IE < 8 is unsupported. - * - * References: - * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement - * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html - * http://url.spec.whatwg.org/#urlutils - * https://github.com/angular/angular.js/pull/2902 - * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ - * - * @param {string} url The URL to be parsed. - * @param {boolean=} parse When true, returns an object for the parsed URL. Otherwise, returns - * a single string that is the normalized URL. - * @returns {object|string} When parse is true, returns the normalized URL as a string. - * Otherwise, returns an object with the following members. - * - * | member name | Description | - * |===============|================| - * | href | A normalized version of the provided URL if it was not an absolute URL | - * | protocol | The protocol including the trailing colon | - * | host | The host and port (if the port is non-default) of the normalizedUrl | - * - * These fields from the UrlUtils interface are currently not needed and hence not returned. - * - * | member name | Description | - * |===============|================| - * | hostname | The host without the port of the normalizedUrl | - * | pathname | The path following the host in the normalizedUrl | - * | hash | The URL hash if present | - * | search | The query string | - * - */ - function resolve(url, parse) { - var href = url; - if (msie) { - // Normalize before parse. Refer Implementation Notes on why this is - // done in two steps on IE. - urlParsingNode.setAttribute("href", href); - href = urlParsingNode.href; - } - urlParsingNode.setAttribute('href', href); - - if (!parse) { - return urlParsingNode.href; - } - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol, - host: urlParsingNode.host - // Currently unused and hence commented out. - // hostname: urlParsingNode.hostname, - // port: urlParsingNode.port, - // pathname: urlParsingNode.pathname, - // hash: urlParsingNode.hash, - // search: urlParsingNode.search - }; - } - - return { - resolve: resolve, - /** - * Parse a request URL and determine whether this is a same-origin request as the application document. - * - * @param {string|object} requestUrl The url of the request as a string that will be resolved - * or a parsed URL object. - * @returns {boolean} Whether the request is for the same origin as the application document. - */ - isSameOrigin: function isSameOrigin(requestUrl) { - var parsed = (typeof requestUrl === 'string') ? resolve(requestUrl, true) : requestUrl; - return (parsed.protocol === originUrl.protocol && - parsed.host === originUrl.host); - } - }; - }]; -} - -/** - * @ngdoc object - * @name ng.$window - * - * @description - * A reference to the browser's `window` object. While `window` - * is globally available in JavaScript, it causes testability problems, because - * it is a global variable. In angular we always refer to it through the - * `$window` service, so it may be overridden, removed or mocked for testing. - * - * Expressions, like the one defined for the `ngClick` directive in the example - * below, are evaluated with respect to the current scope. Therefore, there is - * no risk of inadvertently coding in a dependency on a global value in such an - * expression. - * - * @example - - - -
- - -
-
- - it('should display the greeting in the input box', function() { - input('greeting').enter('Hello, E2E Tests'); - // If we click the button it will block the test runner - // element(':button').click(); - }); - -
- */ -function $WindowProvider(){ - this.$get = valueFn(window); -} - -/** - * @ngdoc object - * @name ng.$filterProvider - * @description - * - * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To - * achieve this a filter definition consists of a factory function which is annotated with dependencies and is - * responsible for creating a filter function. - * - *
- *   // Filter registration
- *   function MyModule($provide, $filterProvider) {
- *     // create a service to demonstrate injection (not always needed)
- *     $provide.value('greet', function(name){
- *       return 'Hello ' + name + '!';
- *     });
- *
- *     // register a filter factory which uses the
- *     // greet service to demonstrate DI.
- *     $filterProvider.register('greet', function(greet){
- *       // return the filter function which uses the greet service
- *       // to generate salutation
- *       return function(text) {
- *         // filters need to be forgiving so check input validity
- *         return text && greet(text) || text;
- *       };
- *     });
- *   }
- * 
- * - * The filter function is registered with the `$injector` under the filter name suffix with `Filter`. - *
- *   it('should be the same instance', inject(
- *     function($filterProvider) {
- *       $filterProvider.register('reverse', function(){
- *         return ...;
- *       });
- *     },
- *     function($filter, reverseFilter) {
- *       expect($filter('reverse')).toBe(reverseFilter);
- *     });
- * 
- * - * - * For more information about how angular filters work, and how to create your own filters, see - * {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer - * Guide. - */ -/** - * @ngdoc method - * @name ng.$filterProvider#register - * @methodOf ng.$filterProvider - * @description - * Register filter factory function. - * - * @param {String} name Name of the filter. - * @param {function} fn The filter factory function which is injectable. - */ - - -/** - * @ngdoc function - * @name ng.$filter - * @function - * @description - * Filters are used for formatting data displayed to the user. - * - * The general syntax in templates is as follows: - * - * {{ expression [| filter_name[:parameter_value] ... ] }} - * - * @param {String} name Name of the filter function to retrieve - * @return {Function} the filter function - */ -$FilterProvider.$inject = ['$provide']; -function $FilterProvider($provide) { - var suffix = 'Filter'; - - function register(name, factory) { - return $provide.factory(name + suffix, factory); - } - this.register = register; - - this.$get = ['$injector', function($injector) { - return function(name) { - return $injector.get(name + suffix); - } - }]; - - //////////////////////////////////////// - - register('currency', currencyFilter); - register('date', dateFilter); - register('filter', filterFilter); - register('json', jsonFilter); - register('limitTo', limitToFilter); - register('lowercase', lowercaseFilter); - register('number', numberFilter); - register('orderBy', orderByFilter); - register('uppercase', uppercaseFilter); -} - -/** - * @ngdoc filter - * @name ng.filter:filter - * @function - * - * @description - * Selects a subset of items from `array` and returns it as a new array. - * - * Note: This function is used to augment the `Array` type in Angular expressions. See - * {@link ng.$filter} for more information about Angular arrays. - * - * @param {Array} array The source array. - * @param {string|Object|function()} expression The predicate to be used for selecting items from - * `array`. - * - * Can be one of: - * - * - `string`: Predicate that results in a substring match using the value of `expression` - * string. All strings or objects with string properties in `array` that contain this string - * will be returned. The predicate can be negated by prefixing the string with `!`. - * - * - `Object`: A pattern object can be used to filter specific properties on objects contained - * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items - * which have property `name` containing "M" and property `phone` containing "1". A special - * property name `$` can be used (as in `{$:"text"}`) to accept a match against any - * property of the object. That's equivalent to the simple substring match with a `string` - * as described above. - * - * - `function`: A predicate function can be used to write arbitrary filters. The function is - * called for each element of `array`. The final result is an array of those elements that - * the predicate returned true for. - * - * @param {function(expected, actual)|true|undefined} comparator Comparator which is used in - * determining if the expected value (from the filter expression) and actual value (from - * the object in the array) should be considered a match. - * - * Can be one of: - * - * - `function(expected, actual)`: - * The function will be given the object value and the predicate value to compare and - * should return true if the item should be included in filtered result. - * - * - `true`: A shorthand for `function(expected, actual) { return angular.equals(expected, actual)}`. - * this is essentially strict comparison of expected and actual. - * - * - `false|undefined`: A short hand for a function which will look for a substring match in case - * insensitive way. - * - * @example - - -
- - Search: -
NamePhone
{{friend.name}} {{friend.phone}}
- - - - - -
NamePhone
{{friend.name}}{{friend.phone}}
-
- Any:
- Name only
- Phone only
- Equality
- - - - - - -
NamePhone
{{friend.name}}{{friend.phone}}
-
- - it('should search across all fields when filtering with a string', function() { - input('searchText').enter('m'); - expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). - toEqual(['Mary', 'Mike', 'Adam']); - - input('searchText').enter('76'); - expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). - toEqual(['John', 'Julie']); - }); - - it('should search in specific fields when filtering with a predicate object', function() { - input('search.$').enter('i'); - expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). - toEqual(['Mary', 'Mike', 'Julie', 'Juliette']); - }); - it('should use a equal comparison when comparator is true', function() { - input('search.name').enter('Julie'); - input('strict').check(); - expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). - toEqual(['Julie']); - }); - -
- */ -function filterFilter() { - return function(array, expression, comperator) { - if (!isArray(array)) return array; - var predicates = []; - predicates.check = function(value) { - for (var j = 0; j < predicates.length; j++) { - if(!predicates[j](value)) { - return false; - } - } - return true; - }; - switch(typeof comperator) { - case "function": - break; - case "boolean": - if(comperator == true) { - comperator = function(obj, text) { - return angular.equals(obj, text); - } - break; - } - default: - comperator = function(obj, text) { - text = (''+text).toLowerCase(); - return (''+obj).toLowerCase().indexOf(text) > -1 - }; - } - var search = function(obj, text){ - if (typeof text == 'string' && text.charAt(0) === '!') { - return !search(obj, text.substr(1)); - } - switch (typeof obj) { - case "boolean": - case "number": - case "string": - return comperator(obj, text); - case "object": - switch (typeof text) { - case "object": - return comperator(obj, text); - break; - default: - for ( var objKey in obj) { - if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { - return true; - } - } - break; - } - return false; - case "array": - for ( var i = 0; i < obj.length; i++) { - if (search(obj[i], text)) { - return true; - } - } - return false; - default: - return false; - } - }; - switch (typeof expression) { - case "boolean": - case "number": - case "string": - expression = {$:expression}; - case "object": - for (var key in expression) { - if (key == '$') { - (function() { - if (!expression[key]) return; - var path = key - predicates.push(function(value) { - return search(value, expression[path]); - }); - })(); - } else { - (function() { - if (!expression[key]) return; - var path = key; - predicates.push(function(value) { - return search(getter(value,path), expression[path]); - }); - })(); - } - } - break; - case 'function': - predicates.push(expression); - break; - default: - return array; - } - var filtered = []; - for ( var j = 0; j < array.length; j++) { - var value = array[j]; - if (predicates.check(value)) { - filtered.push(value); - } - } - return filtered; - } -} - -/** - * @ngdoc filter - * @name ng.filter:currency - * @function - * - * @description - * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default - * symbol for current locale is used. - * - * @param {number} amount Input to filter. - * @param {string=} symbol Currency symbol or identifier to be displayed. - * @returns {string} Formatted number. - * - * - * @example - - - -
-
- default currency symbol ($): {{amount | currency}}
- custom currency identifier (USD$): {{amount | currency:"USD$"}} -
-
- - it('should init with 1234.56', function() { - expect(binding('amount | currency')).toBe('$1,234.56'); - expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56'); - }); - it('should update', function() { - input('amount').enter('-1234'); - expect(binding('amount | currency')).toBe('($1,234.00)'); - expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)'); - }); - -
- */ -currencyFilter.$inject = ['$locale']; -function currencyFilter($locale) { - var formats = $locale.NUMBER_FORMATS; - return function(amount, currencySymbol){ - if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; - return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). - replace(/\u00A4/g, currencySymbol); - }; -} - -/** - * @ngdoc filter - * @name ng.filter:number - * @function - * - * @description - * Formats a number as text. - * - * If the input is not a number an empty string is returned. - * - * @param {number|string} number Number to format. - * @param {(number|string)=} fractionSize Number of decimal places to round the number to. - * If this is not provided then the fraction size is computed from the current locale's number - * formatting pattern. In the case of the default locale, it will be 3. - * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. - * - * @example - - - -
- Enter number:
- Default formatting: {{val | number}}
- No fractions: {{val | number:0}}
- Negative number: {{-val | number:4}} -
-
- - it('should format numbers', function() { - expect(binding('val | number')).toBe('1,234.568'); - expect(binding('val | number:0')).toBe('1,235'); - expect(binding('-val | number:4')).toBe('-1,234.5679'); - }); - - it('should update', function() { - input('val').enter('3374.333'); - expect(binding('val | number')).toBe('3,374.333'); - expect(binding('val | number:0')).toBe('3,374'); - expect(binding('-val | number:4')).toBe('-3,374.3330'); - }); - -
- */ - - -numberFilter.$inject = ['$locale']; -function numberFilter($locale) { - var formats = $locale.NUMBER_FORMATS; - return function(number, fractionSize) { - return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, - fractionSize); - }; -} - -var DECIMAL_SEP = '.'; -function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { - if (isNaN(number) || !isFinite(number)) return ''; - - var isNegative = number < 0; - number = Math.abs(number); - var numStr = number + '', - formatedText = '', - parts = []; - - var hasExponent = false; - if (numStr.indexOf('e') !== -1) { - var match = numStr.match(/([\d\.]+)e(-?)(\d+)/); - if (match && match[2] == '-' && match[3] > fractionSize + 1) { - numStr = '0'; - } else { - formatedText = numStr; - hasExponent = true; - } - } - - if (!hasExponent) { - var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; - - // determine fractionSize if it is not specified - if (isUndefined(fractionSize)) { - fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); - } - - var pow = Math.pow(10, fractionSize); - number = Math.round(number * pow) / pow; - var fraction = ('' + number).split(DECIMAL_SEP); - var whole = fraction[0]; - fraction = fraction[1] || ''; - - var pos = 0, - lgroup = pattern.lgSize, - group = pattern.gSize; - - if (whole.length >= (lgroup + group)) { - pos = whole.length - lgroup; - for (var i = 0; i < pos; i++) { - if ((pos - i)%group === 0 && i !== 0) { - formatedText += groupSep; - } - formatedText += whole.charAt(i); - } - } - - for (i = pos; i < whole.length; i++) { - if ((whole.length - i)%lgroup === 0 && i !== 0) { - formatedText += groupSep; - } - formatedText += whole.charAt(i); - } - - // format fraction part. - while(fraction.length < fractionSize) { - fraction += '0'; - } - - if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); - } else { - - if (fractionSize > 0 && number > -1 && number < 1) { - formatedText = number.toFixed(fractionSize); - } - } - - parts.push(isNegative ? pattern.negPre : pattern.posPre); - parts.push(formatedText); - parts.push(isNegative ? pattern.negSuf : pattern.posSuf); - return parts.join(''); -} - -function padNumber(num, digits, trim) { - var neg = ''; - if (num < 0) { - neg = '-'; - num = -num; - } - num = '' + num; - while(num.length < digits) num = '0' + num; - if (trim) - num = num.substr(num.length - digits); - return neg + num; -} - - -function dateGetter(name, size, offset, trim) { - offset = offset || 0; - return function(date) { - var value = date['get' + name](); - if (offset > 0 || value > -offset) - value += offset; - if (value === 0 && offset == -12 ) value = 12; - return padNumber(value, size, trim); - }; -} - -function dateStrGetter(name, shortForm) { - return function(date, formats) { - var value = date['get' + name](); - var get = uppercase(shortForm ? ('SHORT' + name) : name); - - return formats[get][value]; - }; -} - -function timeZoneGetter(date) { - var zone = -1 * date.getTimezoneOffset(); - var paddedZone = (zone >= 0) ? "+" : ""; - - paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + - padNumber(Math.abs(zone % 60), 2); - - return paddedZone; -} - -function ampmGetter(date, formats) { - return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; -} - -var DATE_FORMATS = { - yyyy: dateGetter('FullYear', 4), - yy: dateGetter('FullYear', 2, 0, true), - y: dateGetter('FullYear', 1), - MMMM: dateStrGetter('Month'), - MMM: dateStrGetter('Month', true), - MM: dateGetter('Month', 2, 1), - M: dateGetter('Month', 1, 1), - dd: dateGetter('Date', 2), - d: dateGetter('Date', 1), - HH: dateGetter('Hours', 2), - H: dateGetter('Hours', 1), - hh: dateGetter('Hours', 2, -12), - h: dateGetter('Hours', 1, -12), - mm: dateGetter('Minutes', 2), - m: dateGetter('Minutes', 1), - ss: dateGetter('Seconds', 2), - s: dateGetter('Seconds', 1), - // while ISO 8601 requires fractions to be prefixed with `.` or `,` - // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions - sss: dateGetter('Milliseconds', 3), - EEEE: dateStrGetter('Day'), - EEE: dateStrGetter('Day', true), - a: ampmGetter, - Z: timeZoneGetter -}; - -var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, - NUMBER_STRING = /^\d+$/; - -/** - * @ngdoc filter - * @name ng.filter:date - * @function - * - * @description - * Formats `date` to a string based on the requested `format`. - * - * `format` string can be composed of the following elements: - * - * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) - * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) - * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) - * * `'MMMM'`: Month in year (January-December) - * * `'MMM'`: Month in year (Jan-Dec) - * * `'MM'`: Month in year, padded (01-12) - * * `'M'`: Month in year (1-12) - * * `'dd'`: Day in month, padded (01-31) - * * `'d'`: Day in month (1-31) - * * `'EEEE'`: Day in Week,(Sunday-Saturday) - * * `'EEE'`: Day in Week, (Sun-Sat) - * * `'HH'`: Hour in day, padded (00-23) - * * `'H'`: Hour in day (0-23) - * * `'hh'`: Hour in am/pm, padded (01-12) - * * `'h'`: Hour in am/pm, (1-12) - * * `'mm'`: Minute in hour, padded (00-59) - * * `'m'`: Minute in hour (0-59) - * * `'ss'`: Second in minute, padded (00-59) - * * `'s'`: Second in minute (0-59) - * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999) - * * `'a'`: am/pm marker - * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) - * - * `format` string can also be one of the following predefined - * {@link guide/i18n localizable formats}: - * - * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale - * (e.g. Sep 3, 2010 12:05:08 pm) - * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) - * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale - * (e.g. Friday, September 3, 2010) - * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010) - * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) - * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) - * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) - * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) - * - * `format` string can contain literal values. These need to be quoted with single quotes (e.g. - * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence - * (e.g. `"h 'o''clock'"`). - * - * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or - * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its - * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is - * specified in the string input, the time is considered to be in the local timezone. - * @param {string=} format Formatting rules (see Description). If not specified, - * `mediumDate` is used. - * @returns {string} Formatted string or the input if input is not recognized as date/millis. - * - * @example - - - {{1288323623006 | date:'medium'}}: - {{1288323623006 | date:'medium'}}
- {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}: - {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}
- {{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}: - {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}
-
- - it('should format date', function() { - expect(binding("1288323623006 | date:'medium'")). - toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); - expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). - toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/); - expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). - toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); - }); - -
- */ -dateFilter.$inject = ['$locale']; -function dateFilter($locale) { - - - var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; - // 1 2 3 4 5 6 7 8 9 10 11 - function jsonStringToDate(string) { - var match; - if (match = string.match(R_ISO8601_STR)) { - var date = new Date(0), - tzHour = 0, - tzMin = 0, - dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, - timeSetter = match[8] ? date.setUTCHours : date.setHours; - - if (match[9]) { - tzHour = int(match[9] + match[10]); - tzMin = int(match[9] + match[11]); - } - dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3])); - var h = int(match[4]||0) - tzHour; - var m = int(match[5]||0) - tzMin - var s = int(match[6]||0); - var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000); - timeSetter.call(date, h, m, s, ms); - return date; - } - return string; - } - - - return function(date, format) { - var text = '', - parts = [], - fn, match; - - format = format || 'mediumDate'; - format = $locale.DATETIME_FORMATS[format] || format; - if (isString(date)) { - if (NUMBER_STRING.test(date)) { - date = int(date); - } else { - date = jsonStringToDate(date); - } - } - - if (isNumber(date)) { - date = new Date(date); - } - - if (!isDate(date)) { - return date; - } - - while(format) { - match = DATE_FORMATS_SPLIT.exec(format); - if (match) { - parts = concat(parts, match, 1); - format = parts.pop(); - } else { - parts.push(format); - format = null; - } - } - - forEach(parts, function(value){ - fn = DATE_FORMATS[value]; - text += fn ? fn(date, $locale.DATETIME_FORMATS) - : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); - }); - - return text; - }; -} - - -/** - * @ngdoc filter - * @name ng.filter:json - * @function - * - * @description - * Allows you to convert a JavaScript object into JSON string. - * - * This filter is mostly useful for debugging. When using the double curly {{value}} notation - * the binding is automatically converted to JSON. - * - * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. - * @returns {string} JSON string. - * - * - * @example: - - -
{{ {'name':'value'} | json }}
-
- - it('should jsonify filtered objects', function() { - expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/); - }); - -
- * - */ -function jsonFilter() { - return function(object) { - return toJson(object, true); - }; -} - - -/** - * @ngdoc filter - * @name ng.filter:lowercase - * @function - * @description - * Converts string to lowercase. - * @see angular.lowercase - */ -var lowercaseFilter = valueFn(lowercase); - - -/** - * @ngdoc filter - * @name ng.filter:uppercase - * @function - * @description - * Converts string to uppercase. - * @see angular.uppercase - */ -var uppercaseFilter = valueFn(uppercase); - -/** - * @ngdoc function - * @name ng.filter:limitTo - * @function - * - * @description - * Creates a new array or string containing only a specified number of elements. The elements - * are taken from either the beginning or the end of the source array or string, as specified by - * the value and sign (positive or negative) of `limit`. - * - * Note: This function is used to augment the `Array` type in Angular expressions. See - * {@link ng.$filter} for more information about Angular arrays. - * - * @param {Array|string} input Source array or string to be limited. - * @param {string|number} limit The length of the returned array or string. If the `limit` number - * is positive, `limit` number of items from the beginning of the source array/string are copied. - * If the number is negative, `limit` number of items from the end of the source array/string - * are copied. The `limit` will be trimmed if it exceeds `array.length` - * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array - * had less than `limit` elements. - * - * @example - - - -
- Limit {{numbers}} to: -

Output numbers: {{ numbers | limitTo:numLimit }}

- Limit {{letters}} to: -

Output letters: {{ letters | limitTo:letterLimit }}

-
-
- - it('should limit the number array to first three items', function() { - expect(element('.doc-example-live input[ng-model=numLimit]').val()).toBe('3'); - expect(element('.doc-example-live input[ng-model=letterLimit]').val()).toBe('3'); - expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3]'); - expect(binding('letters | limitTo:letterLimit')).toEqual('abc'); - }); - - it('should update the output when -3 is entered', function() { - input('numLimit').enter(-3); - input('letterLimit').enter(-3); - expect(binding('numbers | limitTo:numLimit')).toEqual('[7,8,9]'); - expect(binding('letters | limitTo:letterLimit')).toEqual('ghi'); - }); - - it('should not exceed the maximum size of input array', function() { - input('numLimit').enter(100); - input('letterLimit').enter(100); - expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3,4,5,6,7,8,9]'); - expect(binding('letters | limitTo:letterLimit')).toEqual('abcdefghi'); - }); - -
- */ -function limitToFilter(){ - return function(input, limit) { - if (!isArray(input) && !isString(input)) return input; - - limit = int(limit); - - if (isString(input)) { - //NaN check on limit - if (limit) { - return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); - } else { - return ""; - } - } - - var out = [], - i, n; - - // if abs(limit) exceeds maximum length, trim it - if (limit > input.length) - limit = input.length; - else if (limit < -input.length) - limit = -input.length; - - if (limit > 0) { - i = 0; - n = limit; - } else { - i = input.length + limit; - n = input.length; - } - - for (; i} expression A predicate to be - * used by the comparator to determine the order of elements. - * - * Can be one of: - * - * - `function`: Getter function. The result of this function will be sorted using the - * `<`, `=`, `>` operator. - * - `string`: An Angular expression which evaluates to an object to order by, such as 'name' - * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control - * ascending or descending sort order (for example, +name or -name). - * - `Array`: An array of function or string predicates. The first predicate in the array - * is used for sorting, but when two items are equivalent, the next predicate is used. - * - * @param {boolean=} reverse Reverse the order the array. - * @returns {Array} Sorted copy of the source array. - * - * @example - - - -
-
Sorting predicate = {{predicate}}; reverse = {{reverse}}
-
- [
unsorted ] - - - - - - - - - - - -
Name - (^)Phone NumberAge
{{friend.name}}{{friend.phone}}{{friend.age}}
-
- - - it('should be reverse ordered by aged', function() { - expect(binding('predicate')).toBe('-age'); - expect(repeater('table.friend', 'friend in friends').column('friend.age')). - toEqual(['35', '29', '21', '19', '10']); - expect(repeater('table.friend', 'friend in friends').column('friend.name')). - toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); - }); - - it('should reorder the table when user selects different predicate', function() { - element('.doc-example-live a:contains("Name")').click(); - expect(repeater('table.friend', 'friend in friends').column('friend.name')). - toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); - expect(repeater('table.friend', 'friend in friends').column('friend.age')). - toEqual(['35', '10', '29', '19', '21']); - - element('.doc-example-live a:contains("Phone")').click(); - expect(repeater('table.friend', 'friend in friends').column('friend.phone')). - toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); - expect(repeater('table.friend', 'friend in friends').column('friend.name')). - toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); - }); - - - */ -orderByFilter.$inject = ['$parse']; -function orderByFilter($parse){ - return function(array, sortPredicate, reverseOrder) { - if (!isArray(array)) return array; - if (!sortPredicate) return array; - sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; - sortPredicate = map(sortPredicate, function(predicate){ - var descending = false, get = predicate || identity; - if (isString(predicate)) { - if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { - descending = predicate.charAt(0) == '-'; - predicate = predicate.substring(1); - } - get = $parse(predicate); - } - return reverseComparator(function(a,b){ - return compare(get(a),get(b)); - }, descending); - }); - var arrayCopy = []; - for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } - return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); - - function comparator(o1, o2){ - for ( var i = 0; i < sortPredicate.length; i++) { - var comp = sortPredicate[i](o1, o2); - if (comp !== 0) return comp; - } - return 0; - } - function reverseComparator(comp, descending) { - return toBoolean(descending) - ? function(a,b){return comp(b,a);} - : comp; - } - function compare(v1, v2){ - var t1 = typeof v1; - var t2 = typeof v2; - if (t1 == t2) { - if (t1 == "string") v1 = v1.toLowerCase(); - if (t1 == "string") v2 = v2.toLowerCase(); - if (v1 === v2) return 0; - return v1 < v2 ? -1 : 1; - } else { - return t1 < t2 ? -1 : 1; - } - } - } -} - -function ngDirective(directive) { - if (isFunction(directive)) { - directive = { - link: directive - } - } - directive.restrict = directive.restrict || 'AC'; - return valueFn(directive); -} - -/** - * @ngdoc directive - * @name ng.directive:a - * @restrict E - * - * @description - * Modifies the default behavior of html A tag, so that the default action is prevented when href - * attribute is empty. - * - * The reasoning for this change is to allow easy creation of action links with `ngClick` directive - * without changing the location or causing page reloads, e.g.: - * `Save` - */ -var htmlAnchorDirective = valueFn({ - restrict: 'E', - compile: function(element, attr) { - - if (msie <= 8) { - - // turn link into a stylable link in IE - // but only if it doesn't have name attribute, in which case it's an anchor - if (!attr.href && !attr.name) { - attr.$set('href', ''); - } - - // add a comment node to anchors to workaround IE bug that causes element content to be reset - // to new attribute content if attribute is updated with value containing @ and element also - // contains value with @ - // see issue #1949 - element.append(document.createComment('IE fix')); - } - - return function(scope, element) { - element.on('click', function(event){ - // if we have no href url, then don't navigate anywhere. - if (!element.attr('href')) { - event.preventDefault(); - } - }); - } - } -}); - -/** - * @ngdoc directive - * @name ng.directive:ngHref - * @restrict A - * - * @description - * Using Angular markup like {{hash}} in an href attribute makes - * the page open to a wrong URL, if the user clicks that link before - * angular has a chance to replace the {{hash}} with actual URL, the - * link will be broken and will most likely return a 404 error. - * The `ngHref` directive solves this problem. - * - * The buggy way to write it: - *
- * 
- * 
- * - * The correct way to write it: - *
- * 
- * 
- * - * @element A - * @param {template} ngHref any string which can contain `{{}}` markup. - * - * @example - * This example uses `link` variable inside `href` attribute: - - -
-
link 1 (link, don't reload)
- link 2 (link, don't reload)
- link 3 (link, reload!)
- anchor (link, don't reload)
- anchor (no link)
- link (link, change location) - - - it('should execute ng-click but not reload when href without value', function() { - element('#link-1').click(); - expect(input('value').val()).toEqual('1'); - expect(element('#link-1').attr('href')).toBe(""); - }); - - it('should execute ng-click but not reload when href empty string', function() { - element('#link-2').click(); - expect(input('value').val()).toEqual('2'); - expect(element('#link-2').attr('href')).toBe(""); - }); - - it('should execute ng-click and change url when ng-href specified', function() { - expect(element('#link-3').attr('href')).toBe("/123"); - - element('#link-3').click(); - expect(browser().window().path()).toEqual('/123'); - }); - - it('should execute ng-click but not reload when href empty string and name specified', function() { - element('#link-4').click(); - expect(input('value').val()).toEqual('4'); - expect(element('#link-4').attr('href')).toBe(''); - }); - - it('should execute ng-click but not reload when no href but name specified', function() { - element('#link-5').click(); - expect(input('value').val()).toEqual('5'); - expect(element('#link-5').attr('href')).toBe(undefined); - }); - - it('should only change url when only ng-href', function() { - input('value').enter('6'); - expect(element('#link-6').attr('href')).toBe('6'); - - element('#link-6').click(); - expect(browser().location().url()).toEqual('/6'); - }); - - - */ - -/** - * @ngdoc directive - * @name ng.directive:ngSrc - * @restrict A - * - * @description - * Using Angular markup like `{{hash}}` in a `src` attribute doesn't - * work right: The browser will fetch from the URL with the literal - * text `{{hash}}` until Angular replaces the expression inside - * `{{hash}}`. The `ngSrc` directive solves this problem. - * - * The buggy way to write it: - *
- * 
- * 
- * - * The correct way to write it: - *
- * 
- * 
- * - * @element IMG - * @param {template} ngSrc any string which can contain `{{}}` markup. - */ - -/** - * @ngdoc directive - * @name ng.directive:ngSrcset - * @restrict A - * - * @description - * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't - * work right: The browser will fetch from the URL with the literal - * text `{{hash}}` until Angular replaces the expression inside - * `{{hash}}`. The `ngSrcset` directive solves this problem. - * - * The buggy way to write it: - *
- * 
- * 
- * - * The correct way to write it: - *
- * 
- * 
- * - * @element IMG - * @param {template} ngSrcset any string which can contain `{{}}` markup. - */ - -/** - * @ngdoc directive - * @name ng.directive:ngDisabled - * @restrict A - * - * @description - * - * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: - *
- * 
- * - *
- *
- * - * The HTML specs do not require browsers to preserve the special attributes such as disabled. - * (The presence of them means true and absence means false) - * This prevents the angular compiler from correctly retrieving the binding expression. - * To solve this problem, we introduce the `ngDisabled` directive. - * - * @example - - - Click me to toggle:
- -
- - it('should toggle button', function() { - expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy(); - input('checked').check(); - expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy(); - }); - -
- * - * @element INPUT - * @param {expression} ngDisabled Angular expression that will be evaluated. - */ - - -/** - * @ngdoc directive - * @name ng.directive:ngChecked - * @restrict A - * - * @description - * The HTML specs do not require browsers to preserve the special attributes such as checked. - * (The presence of them means true and absence means false) - * This prevents the angular compiler from correctly retrieving the binding expression. - * To solve this problem, we introduce the `ngChecked` directive. - * @example - - - Check me to check both:
- -
- - it('should check both checkBoxes', function() { - expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy(); - input('master').check(); - expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy(); - }); - -
- * - * @element INPUT - * @param {expression} ngChecked Angular expression that will be evaluated. - */ - - -/** - * @ngdoc directive - * @name ng.directive:ngReadonly - * @restrict A - * - * @description - * The HTML specs do not require browsers to preserve the special attributes such as readonly. - * (The presence of them means true and absence means false) - * This prevents the angular compiler from correctly retrieving the binding expression. - * To solve this problem, we introduce the `ngReadonly` directive. - * @example - - - Check me to make text readonly:
- -
- - it('should toggle readonly attr', function() { - expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy(); - input('checked').check(); - expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy(); - }); - -
- * - * @element INPUT - * @param {string} expression Angular expression that will be evaluated. - */ - - -/** - * @ngdoc directive - * @name ng.directive:ngSelected - * @restrict A - * - * @description - * The HTML specs do not require browsers to preserve the special attributes such as selected. - * (The presence of them means true and absence means false) - * This prevents the angular compiler from correctly retrieving the binding expression. - * To solve this problem, we introduced the `ngSelected` directive. - * @example - - - Check me to select:
- -
- - it('should select Greetings!', function() { - expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy(); - input('selected').check(); - expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy(); - }); - -
- * - * @element OPTION - * @param {string} expression Angular expression that will be evaluated. - */ - -/** - * @ngdoc directive - * @name ng.directive:ngOpen - * @restrict A - * - * @description - * The HTML specs do not require browsers to preserve the special attributes such as open. - * (The presence of them means true and absence means false) - * This prevents the angular compiler from correctly retrieving the binding expression. - * To solve this problem, we introduce the `ngOpen` directive. - * - * @example - - - Check me check multiple:
-
- Show/Hide me -
-
- - it('should toggle open', function() { - expect(element('#details').prop('open')).toBeFalsy(); - input('open').check(); - expect(element('#details').prop('open')).toBeTruthy(); - }); - -
- * - * @element DETAILS - * @param {string} expression Angular expression that will be evaluated. - */ - -var ngAttributeAliasDirectives = {}; - - -// boolean attrs are evaluated -forEach(BOOLEAN_ATTR, function(propName, attrName) { - // binding to multiple is not supported - if (propName == "multiple") return; - - var normalized = directiveNormalize('ng-' + attrName); - ngAttributeAliasDirectives[normalized] = function() { - return { - priority: 100, - compile: function() { - return function(scope, element, attr) { - scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { - attr.$set(attrName, !!value); - }); - }; - } - }; - }; -}); - - -// ng-src, ng-srcset, ng-href are interpolated -forEach(['src', 'srcset', 'href'], function(attrName) { - var normalized = directiveNormalize('ng-' + attrName); - ngAttributeAliasDirectives[normalized] = function() { - return { - priority: 99, // it needs to run after the attributes are interpolated - link: function(scope, element, attr) { - attr.$observe(normalized, function(value) { - if (!value) - return; - - attr.$set(attrName, value); - - // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist - // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need - // to set the property as well to achieve the desired effect. - // we use attr[attrName] value since $set can sanitize the url. - if (msie) element.prop(attrName, attr[attrName]); - }); - } - }; - }; -}); - -var nullFormCtrl = { - $addControl: noop, - $removeControl: noop, - $setValidity: noop, - $setDirty: noop, - $setPristine: noop -}; - -/** - * @ngdoc object - * @name ng.directive:form.FormController - * - * @property {boolean} $pristine True if user has not interacted with the form yet. - * @property {boolean} $dirty True if user has already interacted with the form. - * @property {boolean} $valid True if all of the containing forms and controls are valid. - * @property {boolean} $invalid True if at least one containing control or form is invalid. - * - * @property {Object} $error Is an object hash, containing references to all invalid controls or - * forms, where: - * - * - keys are validation tokens (error names) — such as `required`, `url` or `email`), - * - values are arrays of controls or forms that are invalid with given error. - * - * @description - * `FormController` keeps track of all its controls and nested forms as well as state of them, - * such as being valid/invalid or dirty/pristine. - * - * Each {@link ng.directive:form form} directive creates an instance - * of `FormController`. - * - */ -//asks for $scope to fool the BC controller module -FormController.$inject = ['$element', '$attrs', '$scope']; -function FormController(element, attrs) { - var form = this, - parentForm = element.parent().controller('form') || nullFormCtrl, - invalidCount = 0, // used to easily determine if we are valid - errors = form.$error = {}, - controls = []; - - // init state - form.$name = attrs.name || attrs.ngForm; - form.$dirty = false; - form.$pristine = true; - form.$valid = true; - form.$invalid = false; - - parentForm.$addControl(form); - - // Setup initial state of the control - element.addClass(PRISTINE_CLASS); - toggleValidCss(true); - - // convenience method for easy toggling of classes - function toggleValidCss(isValid, validationErrorKey) { - validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; - element. - removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). - addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); - } - - /** - * @ngdoc function - * @name ng.directive:form.FormController#$addControl - * @methodOf ng.directive:form.FormController - * - * @description - * Register a control with the form. - * - * Input elements using ngModelController do this automatically when they are linked. - */ - form.$addControl = function(control) { - controls.push(control); - - if (control.$name && !form.hasOwnProperty(control.$name)) { - form[control.$name] = control; - } - }; - - /** - * @ngdoc function - * @name ng.directive:form.FormController#$removeControl - * @methodOf ng.directive:form.FormController - * - * @description - * Deregister a control from the form. - * - * Input elements using ngModelController do this automatically when they are destroyed. - */ - form.$removeControl = function(control) { - if (control.$name && form[control.$name] === control) { - delete form[control.$name]; - } - forEach(errors, function(queue, validationToken) { - form.$setValidity(validationToken, true, control); - }); - - arrayRemove(controls, control); - }; - - /** - * @ngdoc function - * @name ng.directive:form.FormController#$setValidity - * @methodOf ng.directive:form.FormController - * - * @description - * Sets the validity of a form control. - * - * This method will also propagate to parent forms. - */ - form.$setValidity = function(validationToken, isValid, control) { - var queue = errors[validationToken]; - - if (isValid) { - if (queue) { - arrayRemove(queue, control); - if (!queue.length) { - invalidCount--; - if (!invalidCount) { - toggleValidCss(isValid); - form.$valid = true; - form.$invalid = false; - } - errors[validationToken] = false; - toggleValidCss(true, validationToken); - parentForm.$setValidity(validationToken, true, form); - } - } - - } else { - if (!invalidCount) { - toggleValidCss(isValid); - } - if (queue) { - if (includes(queue, control)) return; - } else { - errors[validationToken] = queue = []; - invalidCount++; - toggleValidCss(false, validationToken); - parentForm.$setValidity(validationToken, false, form); - } - queue.push(control); - - form.$valid = false; - form.$invalid = true; - } - }; - - /** - * @ngdoc function - * @name ng.directive:form.FormController#$setDirty - * @methodOf ng.directive:form.FormController - * - * @description - * Sets the form to a dirty state. - * - * This method can be called to add the 'ng-dirty' class and set the form to a dirty - * state (ng-dirty class). This method will also propagate to parent forms. - */ - form.$setDirty = function() { - element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); - form.$dirty = true; - form.$pristine = false; - parentForm.$setDirty(); - }; - - /** - * @ngdoc function - * @name ng.directive:form.FormController#$setPristine - * @methodOf ng.directive:form.FormController - * - * @description - * Sets the form to its pristine state. - * - * This method can be called to remove the 'ng-dirty' class and set the form to its pristine - * state (ng-pristine class). This method will also propagate to all the controls contained - * in this form. - * - * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after - * saving or resetting it. - */ - form.$setPristine = function () { - element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS); - form.$dirty = false; - form.$pristine = true; - forEach(controls, function(control) { - control.$setPristine(); - }); - }; -} - - -/** - * @ngdoc directive - * @name ng.directive:ngForm - * @restrict EAC - * - * @description - * Nestable alias of {@link ng.directive:form `form`} directive. HTML - * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a - * sub-group of controls needs to be determined. - * - * @param {string=} name|ngForm Name of the form. If specified, the form controller will be published into - * related scope, under this name. - * - */ - - /** - * @ngdoc directive - * @name ng.directive:form - * @restrict E - * - * @description - * Directive that instantiates - * {@link ng.directive:form.FormController FormController}. - * - * If `name` attribute is specified, the form controller is published onto the current scope under - * this name. - * - * # Alias: {@link ng.directive:ngForm `ngForm`} - * - * In angular forms can be nested. This means that the outer form is valid when all of the child - * forms are valid as well. However browsers do not allow nesting of `` elements, for this - * reason angular provides {@link ng.directive:ngForm `ngForm`} alias - * which behaves identical to `` but allows form nesting. - * - * - * # CSS classes - * - `ng-valid` Is set if the form is valid. - * - `ng-invalid` Is set if the form is invalid. - * - `ng-pristine` Is set if the form is pristine. - * - `ng-dirty` Is set if the form is dirty. - * - * - * # Submitting a form and preventing default action - * - * Since the role of forms in client-side Angular applications is different than in classical - * roundtrip apps, it is desirable for the browser not to translate the form submission into a full - * page reload that sends the data to the server. Instead some javascript logic should be triggered - * to handle the form submission in application specific way. - * - * For this reason, Angular prevents the default action (form submission to the server) unless the - * `` element has an `action` attribute specified. - * - * You can use one of the following two ways to specify what javascript method should be called when - * a form is submitted: - * - * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element - * - {@link ng.directive:ngClick ngClick} directive on the first - * button or input field of type submit (input[type=submit]) - * - * To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This - * is because of the following form submission rules coming from the html spec: - * - * - If a form has only one input field then hitting enter in this field triggers form submit - * (`ngSubmit`) - * - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter - * doesn't trigger submit - * - if a form has one or more input fields and one or more buttons or input[type=submit] then - * hitting enter in any of the input fields will trigger the click handler on the *first* button or - * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) - * - * @param {string=} name Name of the form. If specified, the form controller will be published into - * related scope, under this name. - * - * @example - - - - - userType: - Required!
- userType = {{userType}}
- myForm.input.$valid = {{myForm.input.$valid}}
- myForm.input.$error = {{myForm.input.$error}}
- myForm.$valid = {{myForm.$valid}}
- myForm.$error.required = {{!!myForm.$error.required}}
- -
- - it('should initialize to model', function() { - expect(binding('userType')).toEqual('guest'); - expect(binding('myForm.input.$valid')).toEqual('true'); - }); - - it('should be invalid if empty', function() { - input('userType').enter(''); - expect(binding('userType')).toEqual(''); - expect(binding('myForm.input.$valid')).toEqual('false'); - }); - -
- */ -var formDirectiveFactory = function(isNgForm) { - return ['$timeout', function($timeout) { - var formDirective = { - name: 'form', - restrict: 'E', - controller: FormController, - compile: function() { - return { - pre: function(scope, formElement, attr, controller) { - if (!attr.action) { - // we can't use jq events because if a form is destroyed during submission the default - // action is not prevented. see #1238 - // - // IE 9 is not affected because it doesn't fire a submit event and try to do a full - // page reload if the form was destroyed by submission of the form via a click handler - // on a button in the form. Looks like an IE9 specific bug. - var preventDefaultListener = function(event) { - event.preventDefault - ? event.preventDefault() - : event.returnValue = false; // IE - }; - - addEventListenerFn(formElement[0], 'submit', preventDefaultListener); - - // unregister the preventDefault listener so that we don't not leak memory but in a - // way that will achieve the prevention of the default action. - formElement.on('$destroy', function() { - $timeout(function() { - removeEventListenerFn(formElement[0], 'submit', preventDefaultListener); - }, 0, false); - }); - } - - var parentFormCtrl = formElement.parent().controller('form'), - alias = attr.name || attr.ngForm; - - if (alias) { - setter(scope, alias, controller, alias); - } - if (parentFormCtrl) { - formElement.on('$destroy', function() { - parentFormCtrl.$removeControl(controller); - if (alias) { - setter(scope, alias, undefined, alias); - } - extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards - }); - } - } - }; - } - }; - - return isNgForm ? extend(copy(formDirective), {restrict: 'EAC'}) : formDirective; - }]; -}; - -var formDirective = formDirectiveFactory(); -var ngFormDirective = formDirectiveFactory(true); - -var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; -var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/; -var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; - -var inputType = { - - /** - * @ngdoc inputType - * @name ng.directive:input.text - * - * @description - * Standard HTML text input with angular data binding. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} required Adds `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than - * minlength. - * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trimming the - * input. - * - * @example - - - -
- Single word: - - Required! - - Single word only! - - text = {{text}}
- myForm.input.$valid = {{myForm.input.$valid}}
- myForm.input.$error = {{myForm.input.$error}}
- myForm.$valid = {{myForm.$valid}}
- myForm.$error.required = {{!!myForm.$error.required}}
-
-
- - it('should initialize to model', function() { - expect(binding('text')).toEqual('guest'); - expect(binding('myForm.input.$valid')).toEqual('true'); - }); - - it('should be invalid if empty', function() { - input('text').enter(''); - expect(binding('text')).toEqual(''); - expect(binding('myForm.input.$valid')).toEqual('false'); - }); - - it('should be invalid if multi word', function() { - input('text').enter('hello world'); - expect(binding('myForm.input.$valid')).toEqual('false'); - }); - - it('should not be trimmed', function() { - input('text').enter('untrimmed '); - expect(binding('text')).toEqual('untrimmed '); - expect(binding('myForm.input.$valid')).toEqual('true'); - }); - -
- */ - 'text': textInputType, - - - /** - * @ngdoc inputType - * @name ng.directive:input.number - * - * @description - * Text input with number validation and transformation. Sets the `number` validation - * error if not a valid number. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. - * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than - * minlength. - * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
- Number: - - Required! - - Not valid number! - value = {{value}}
- myForm.input.$valid = {{myForm.input.$valid}}
- myForm.input.$error = {{myForm.input.$error}}
- myForm.$valid = {{myForm.$valid}}
- myForm.$error.required = {{!!myForm.$error.required}}
-
-
- - it('should initialize to model', function() { - expect(binding('value')).toEqual('12'); - expect(binding('myForm.input.$valid')).toEqual('true'); - }); - - it('should be invalid if empty', function() { - input('value').enter(''); - expect(binding('value')).toEqual(''); - expect(binding('myForm.input.$valid')).toEqual('false'); - }); - - it('should be invalid if over max', function() { - input('value').enter('123'); - expect(binding('value')).toEqual(''); - expect(binding('myForm.input.$valid')).toEqual('false'); - }); - -
- */ - 'number': numberInputType, - - - /** - * @ngdoc inputType - * @name ng.directive:input.url - * - * @description - * Text input with URL validation. Sets the `url` validation error key if the content is not a - * valid URL. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than - * minlength. - * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
- URL: - - Required! - - Not valid url! - text = {{text}}
- myForm.input.$valid = {{myForm.input.$valid}}
- myForm.input.$error = {{myForm.input.$error}}
- myForm.$valid = {{myForm.$valid}}
- myForm.$error.required = {{!!myForm.$error.required}}
- myForm.$error.url = {{!!myForm.$error.url}}
-
-
- - it('should initialize to model', function() { - expect(binding('text')).toEqual('http://google.com'); - expect(binding('myForm.input.$valid')).toEqual('true'); - }); - - it('should be invalid if empty', function() { - input('text').enter(''); - expect(binding('text')).toEqual(''); - expect(binding('myForm.input.$valid')).toEqual('false'); - }); - - it('should be invalid if not url', function() { - input('text').enter('xxx'); - expect(binding('myForm.input.$valid')).toEqual('false'); - }); - -
- */ - 'url': urlInputType, - - - /** - * @ngdoc inputType - * @name ng.directive:input.email - * - * @description - * Text input with email validation. Sets the `email` validation error key if not a valid email - * address. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than - * minlength. - * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
- Email: - - Required! - - Not valid email! - text = {{text}}
- myForm.input.$valid = {{myForm.input.$valid}}
- myForm.input.$error = {{myForm.input.$error}}
- myForm.$valid = {{myForm.$valid}}
- myForm.$error.required = {{!!myForm.$error.required}}
- myForm.$error.email = {{!!myForm.$error.email}}
-
-
- - it('should initialize to model', function() { - expect(binding('text')).toEqual('me@example.com'); - expect(binding('myForm.input.$valid')).toEqual('true'); - }); - - it('should be invalid if empty', function() { - input('text').enter(''); - expect(binding('text')).toEqual(''); - expect(binding('myForm.input.$valid')).toEqual('false'); - }); - - it('should be invalid if not email', function() { - input('text').enter('xxx'); - expect(binding('myForm.input.$valid')).toEqual('false'); - }); - -
- */ - 'email': emailInputType, - - - /** - * @ngdoc inputType - * @name ng.directive:input.radio - * - * @description - * HTML radio button. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string} value The value to which the expression should be set when selected. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
- Red
- Green
- Blue
- color = {{color}}
-
-
- - it('should change state', function() { - expect(binding('color')).toEqual('blue'); - - input('color').select('red'); - expect(binding('color')).toEqual('red'); - }); - -
- */ - 'radio': radioInputType, - - - /** - * @ngdoc inputType - * @name ng.directive:input.checkbox - * - * @description - * HTML checkbox. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} ngTrueValue The value to which the expression should be set when selected. - * @param {string=} ngFalseValue The value to which the expression should be set when not selected. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
- Value1:
- Value2:
- value1 = {{value1}}
- value2 = {{value2}}
-
-
- - it('should change state', function() { - expect(binding('value1')).toEqual('true'); - expect(binding('value2')).toEqual('YES'); - - input('value1').check(); - input('value2').check(); - expect(binding('value1')).toEqual('false'); - expect(binding('value2')).toEqual('NO'); - }); - -
- */ - 'checkbox': checkboxInputType, - - 'hidden': noop, - 'button': noop, - 'submit': noop, - 'reset': noop -}; - - -function isEmpty(value) { - return isUndefined(value) || value === '' || value === null || value !== value; -} - - -function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { - - var listener = function() { - var value = element.val(); - - // By default we will trim the value - // If the attribute ng-trim exists we will avoid trimming - // e.g. - if (toBoolean(attr.ngTrim || 'T')) { - value = trim(value); - } - - if (ctrl.$viewValue !== value) { - scope.$apply(function() { - ctrl.$setViewValue(value); - }); - } - }; - - // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the - // input event on backspace, delete or cut - if ($sniffer.hasEvent('input')) { - element.on('input', listener); - } else { - var timeout; - - var deferListener = function() { - if (!timeout) { - timeout = $browser.defer(function() { - listener(); - timeout = null; - }); - } - }; - - element.on('keydown', function(event) { - var key = event.keyCode; - - // ignore - // command modifiers arrows - if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; - - deferListener(); - }); - - // if user paste into input using mouse, we need "change" event to catch it - element.on('change', listener); - - // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it - if ($sniffer.hasEvent('paste')) { - element.on('paste cut', deferListener); - } - } - - - ctrl.$render = function() { - element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); - }; - - // pattern validator - var pattern = attr.ngPattern, - patternValidator, - match; - - var validate = function(regexp, value) { - if (isEmpty(value) || regexp.test(value)) { - ctrl.$setValidity('pattern', true); - return value; - } else { - ctrl.$setValidity('pattern', false); - return undefined; - } - }; - - if (pattern) { - match = pattern.match(/^\/(.*)\/([gim]*)$/); - if (match) { - pattern = new RegExp(match[1], match[2]); - patternValidator = function(value) { - return validate(pattern, value) - }; - } else { - patternValidator = function(value) { - var patternObj = scope.$eval(pattern); - - if (!patternObj || !patternObj.test) { - throw minErr('ngPattern')('noregexp', - 'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern, - patternObj, startingTag(element)); - } - return validate(patternObj, value); - }; - } - - ctrl.$formatters.push(patternValidator); - ctrl.$parsers.push(patternValidator); - } - - // min length validator - if (attr.ngMinlength) { - var minlength = int(attr.ngMinlength); - var minLengthValidator = function(value) { - if (!isEmpty(value) && value.length < minlength) { - ctrl.$setValidity('minlength', false); - return undefined; - } else { - ctrl.$setValidity('minlength', true); - return value; - } - }; - - ctrl.$parsers.push(minLengthValidator); - ctrl.$formatters.push(minLengthValidator); - } - - // max length validator - if (attr.ngMaxlength) { - var maxlength = int(attr.ngMaxlength); - var maxLengthValidator = function(value) { - if (!isEmpty(value) && value.length > maxlength) { - ctrl.$setValidity('maxlength', false); - return undefined; - } else { - ctrl.$setValidity('maxlength', true); - return value; - } - }; - - ctrl.$parsers.push(maxLengthValidator); - ctrl.$formatters.push(maxLengthValidator); - } -} - -function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { - textInputType(scope, element, attr, ctrl, $sniffer, $browser); - - ctrl.$parsers.push(function(value) { - var empty = isEmpty(value); - if (empty || NUMBER_REGEXP.test(value)) { - ctrl.$setValidity('number', true); - return value === '' ? null : (empty ? value : parseFloat(value)); - } else { - ctrl.$setValidity('number', false); - return undefined; - } - }); - - ctrl.$formatters.push(function(value) { - return isEmpty(value) ? '' : '' + value; - }); - - if (attr.min) { - var min = parseFloat(attr.min); - var minValidator = function(value) { - if (!isEmpty(value) && value < min) { - ctrl.$setValidity('min', false); - return undefined; - } else { - ctrl.$setValidity('min', true); - return value; - } - }; - - ctrl.$parsers.push(minValidator); - ctrl.$formatters.push(minValidator); - } - - if (attr.max) { - var max = parseFloat(attr.max); - var maxValidator = function(value) { - if (!isEmpty(value) && value > max) { - ctrl.$setValidity('max', false); - return undefined; - } else { - ctrl.$setValidity('max', true); - return value; - } - }; - - ctrl.$parsers.push(maxValidator); - ctrl.$formatters.push(maxValidator); - } - - ctrl.$formatters.push(function(value) { - - if (isEmpty(value) || isNumber(value)) { - ctrl.$setValidity('number', true); - return value; - } else { - ctrl.$setValidity('number', false); - return undefined; - } - }); -} - -function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { - textInputType(scope, element, attr, ctrl, $sniffer, $browser); - - var urlValidator = function(value) { - if (isEmpty(value) || URL_REGEXP.test(value)) { - ctrl.$setValidity('url', true); - return value; - } else { - ctrl.$setValidity('url', false); - return undefined; - } - }; - - ctrl.$formatters.push(urlValidator); - ctrl.$parsers.push(urlValidator); -} - -function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { - textInputType(scope, element, attr, ctrl, $sniffer, $browser); - - var emailValidator = function(value) { - if (isEmpty(value) || EMAIL_REGEXP.test(value)) { - ctrl.$setValidity('email', true); - return value; - } else { - ctrl.$setValidity('email', false); - return undefined; - } - }; - - ctrl.$formatters.push(emailValidator); - ctrl.$parsers.push(emailValidator); -} - -function radioInputType(scope, element, attr, ctrl) { - // make the name unique, if not defined - if (isUndefined(attr.name)) { - element.attr('name', nextUid()); - } - - element.on('click', function() { - if (element[0].checked) { - scope.$apply(function() { - ctrl.$setViewValue(attr.value); - }); - } - }); - - ctrl.$render = function() { - var value = attr.value; - element[0].checked = (value == ctrl.$viewValue); - }; - - attr.$observe('value', ctrl.$render); -} - -function checkboxInputType(scope, element, attr, ctrl) { - var trueValue = attr.ngTrueValue, - falseValue = attr.ngFalseValue; - - if (!isString(trueValue)) trueValue = true; - if (!isString(falseValue)) falseValue = false; - - element.on('click', function() { - scope.$apply(function() { - ctrl.$setViewValue(element[0].checked); - }); - }); - - ctrl.$render = function() { - element[0].checked = ctrl.$viewValue; - }; - - ctrl.$formatters.push(function(value) { - return value === trueValue; - }); - - ctrl.$parsers.push(function(value) { - return value ? trueValue : falseValue; - }); -} - - -/** - * @ngdoc directive - * @name ng.directive:textarea - * @restrict E - * - * @description - * HTML textarea element control with angular data-binding. The data-binding and validation - * properties of this element are exactly the same as those of the - * {@link ng.directive:input input element}. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than - * minlength. - * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - */ - - -/** - * @ngdoc directive - * @name ng.directive:input - * @restrict E - * - * @description - * HTML input element control with angular data-binding. Input control follows HTML5 input types - * and polyfills the HTML5 validation behavior for older browsers. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {boolean=} ngRequired Sets `required` attribute if set to true - * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than - * minlength. - * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
-
- User name: - - Required!
- Last name: - - Too short! - - Too long!
-
-
- user = {{user}}
- myForm.userName.$valid = {{myForm.userName.$valid}}
- myForm.userName.$error = {{myForm.userName.$error}}
- myForm.lastName.$valid = {{myForm.lastName.$valid}}
- myForm.lastName.$error = {{myForm.lastName.$error}}
- myForm.$valid = {{myForm.$valid}}
- myForm.$error.required = {{!!myForm.$error.required}}
- myForm.$error.minlength = {{!!myForm.$error.minlength}}
- myForm.$error.maxlength = {{!!myForm.$error.maxlength}}
-
-
- - it('should initialize to model', function() { - expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}'); - expect(binding('myForm.userName.$valid')).toEqual('true'); - expect(binding('myForm.$valid')).toEqual('true'); - }); - - it('should be invalid if empty when required', function() { - input('user.name').enter(''); - expect(binding('user')).toEqual('{"last":"visitor"}'); - expect(binding('myForm.userName.$valid')).toEqual('false'); - expect(binding('myForm.$valid')).toEqual('false'); - }); - - it('should be valid if empty when min length is set', function() { - input('user.last').enter(''); - expect(binding('user')).toEqual('{"name":"guest","last":""}'); - expect(binding('myForm.lastName.$valid')).toEqual('true'); - expect(binding('myForm.$valid')).toEqual('true'); - }); - - it('should be invalid if less than required min length', function() { - input('user.last').enter('xx'); - expect(binding('user')).toEqual('{"name":"guest"}'); - expect(binding('myForm.lastName.$valid')).toEqual('false'); - expect(binding('myForm.lastName.$error')).toMatch(/minlength/); - expect(binding('myForm.$valid')).toEqual('false'); - }); - - it('should be invalid if longer than max length', function() { - input('user.last').enter('some ridiculously long name'); - expect(binding('user')) - .toEqual('{"name":"guest"}'); - expect(binding('myForm.lastName.$valid')).toEqual('false'); - expect(binding('myForm.lastName.$error')).toMatch(/maxlength/); - expect(binding('myForm.$valid')).toEqual('false'); - }); - -
- */ -var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) { - return { - restrict: 'E', - require: '?ngModel', - link: function(scope, element, attr, ctrl) { - if (ctrl) { - (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer, - $browser); - } - } - }; -}]; - -var VALID_CLASS = 'ng-valid', - INVALID_CLASS = 'ng-invalid', - PRISTINE_CLASS = 'ng-pristine', - DIRTY_CLASS = 'ng-dirty'; - -/** - * @ngdoc object - * @name ng.directive:ngModel.NgModelController - * - * @property {string} $viewValue Actual string value in the view. - * @property {*} $modelValue The value in the model, that the control is bound to. - * @property {Array.} $parsers Array of functions to execute, as a pipeline, whenever - the control reads value from the DOM. Each function is called, in turn, passing the value - through to the next. Used to sanitize / convert the value as well as validation. - For validation, the parsers should update the validity state using - {@link ng.directive:ngModel.NgModelController#$setValidity $setValidity()}, - and return `undefined` for invalid values. - - * - * @property {Array.} $formatters Array of functions to execute, as a pipeline, whenever - the model value changes. Each function is called, in turn, passing the value through to the - next. Used to format / convert values for display in the control and validation. - *
- *      function formatter(value) {
- *        if (value) {
- *          return value.toUpperCase();
- *        }
- *      }
- *      ngModel.$formatters.push(formatter);
- *      
- * @property {Object} $error An object hash with all errors as keys. - * - * @property {boolean} $pristine True if user has not interacted with the control yet. - * @property {boolean} $dirty True if user has already interacted with the control. - * @property {boolean} $valid True if there is no error. - * @property {boolean} $invalid True if at least one error on the control. - * - * @description - * - * `NgModelController` provides API for the `ng-model` directive. The controller contains - * services for data-binding, validation, CSS update, value formatting and parsing. It - * specifically does not contain any logic which deals with DOM rendering or listening to - * DOM events. The `NgModelController` is meant to be extended by other directives where, the - * directive provides DOM manipulation and the `NgModelController` provides the data-binding. - * Note that you cannot use `NgModelController` in a directive with an isolated scope, - * as, in that case, the `ng-model` value gets put into the isolated scope and does not get - * propogated to the parent scope. - * - * - * This example shows how to use `NgModelController` with a custom control to achieve - * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) - * collaborate together to achieve the desired result. - * - * - - [contenteditable] { - border: 1px solid black; - background-color: white; - min-height: 20px; - } - - .ng-invalid { - border: 1px solid red; - } - - - - angular.module('customControl', []). - directive('contenteditable', function() { - return { - restrict: 'A', // only activate on element attribute - require: '?ngModel', // get a hold of NgModelController - link: function(scope, element, attrs, ngModel) { - if(!ngModel) return; // do nothing if no ng-model - - // Specify how UI should be updated - ngModel.$render = function() { - element.html(ngModel.$viewValue || ''); - }; - - // Listen for change events to enable binding - element.on('blur keyup change', function() { - scope.$apply(read); - }); - read(); // initialize - - // Write data to the model - function read() { - var html = element.html(); - // When we clear the content editable the browser leaves a
behind - // If strip-br attribute is provided then we strip this out - if( attrs.stripBr && html == '
' ) { - html = ''; - } - ngModel.$setViewValue(html); - } - } - }; - }); -
- -
-
Change me!
- Required! -
- -
-
- - it('should data-bind and become invalid', function() { - var contentEditable = element('[contenteditable]'); - - expect(contentEditable.text()).toEqual('Change me!'); - input('userContent').enter(''); - expect(contentEditable.text()).toEqual(''); - expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/); - }); - - *
- * - */ -var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', - function($scope, $exceptionHandler, $attr, $element, $parse) { - this.$viewValue = Number.NaN; - this.$modelValue = Number.NaN; - this.$parsers = []; - this.$formatters = []; - this.$viewChangeListeners = []; - this.$pristine = true; - this.$dirty = false; - this.$valid = true; - this.$invalid = false; - this.$name = $attr.name; - - var ngModelGet = $parse($attr.ngModel), - ngModelSet = ngModelGet.assign; - - if (!ngModelSet) { - throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}", - $attr.ngModel, startingTag($element)); - } - - /** - * @ngdoc function - * @name ng.directive:ngModel.NgModelController#$render - * @methodOf ng.directive:ngModel.NgModelController - * - * @description - * Called when the view needs to be updated. It is expected that the user of the ng-model - * directive will implement this method. - */ - this.$render = noop; - - var parentForm = $element.inheritedData('$formController') || nullFormCtrl, - invalidCount = 0, // used to easily determine if we are valid - $error = this.$error = {}; // keep invalid keys here - - - // Setup initial state of the control - $element.addClass(PRISTINE_CLASS); - toggleValidCss(true); - - // convenience method for easy toggling of classes - function toggleValidCss(isValid, validationErrorKey) { - validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; - $element. - removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). - addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); - } - - /** - * @ngdoc function - * @name ng.directive:ngModel.NgModelController#$setValidity - * @methodOf ng.directive:ngModel.NgModelController - * - * @description - * Change the validity state, and notifies the form when the control changes validity. (i.e. it - * does not notify form if given validator is already marked as invalid). - * - * This method should be called by validators - i.e. the parser or formatter functions. - * - * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign - * to `$error[validationErrorKey]=isValid` so that it is available for data-binding. - * The `validationErrorKey` should be in camelCase and will get converted into dash-case - * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` - * class and can be bound to as `{{someForm.someControl.$error.myError}}` . - * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). - */ - this.$setValidity = function(validationErrorKey, isValid) { - if ($error[validationErrorKey] === !isValid) return; - - if (isValid) { - if ($error[validationErrorKey]) invalidCount--; - if (!invalidCount) { - toggleValidCss(true); - this.$valid = true; - this.$invalid = false; - } - } else { - toggleValidCss(false); - this.$invalid = true; - this.$valid = false; - invalidCount++; - } - - $error[validationErrorKey] = !isValid; - toggleValidCss(isValid, validationErrorKey); - - parentForm.$setValidity(validationErrorKey, isValid, this); - }; - - /** - * @ngdoc function - * @name ng.directive:ngModel.NgModelController#$setPristine - * @methodOf ng.directive:ngModel.NgModelController - * - * @description - * Sets the control to its pristine state. - * - * This method can be called to remove the 'ng-dirty' class and set the control to its pristine - * state (ng-pristine class). - */ - this.$setPristine = function () { - this.$dirty = false; - this.$pristine = true; - $element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS); - }; - - /** - * @ngdoc function - * @name ng.directive:ngModel.NgModelController#$setViewValue - * @methodOf ng.directive:ngModel.NgModelController - * - * @description - * Read a value from view. - * - * This method should be called from within a DOM event handler. - * For example {@link ng.directive:input input} or - * {@link ng.directive:select select} directives call it. - * - * It internally calls all `$parsers` (including validators) and updates the `$modelValue` and the actual model path. - * Lastly it calls all registered change listeners. - * - * @param {string} value Value from the view. - */ - this.$setViewValue = function(value) { - this.$viewValue = value; - - // change to dirty - if (this.$pristine) { - this.$dirty = true; - this.$pristine = false; - $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); - parentForm.$setDirty(); - } - - forEach(this.$parsers, function(fn) { - value = fn(value); - }); - - if (this.$modelValue !== value) { - this.$modelValue = value; - ngModelSet($scope, value); - forEach(this.$viewChangeListeners, function(listener) { - try { - listener(); - } catch(e) { - $exceptionHandler(e); - } - }) - } - }; - - // model -> value - var ctrl = this; - - $scope.$watch(function ngModelWatch() { - var value = ngModelGet($scope); - - // if scope model value and ngModel value are out of sync - if (ctrl.$modelValue !== value) { - - var formatters = ctrl.$formatters, - idx = formatters.length; - - ctrl.$modelValue = value; - while(idx--) { - value = formatters[idx](value); - } - - if (ctrl.$viewValue !== value) { - ctrl.$viewValue = value; - ctrl.$render(); - } - } - }); -}]; - - -/** - * @ngdoc directive - * @name ng.directive:ngModel - * - * @element input - * - * @description - * Is a directive that tells Angular to do two-way data binding. It works together with `input`, - * `select`, `textarea` and even custom form controls that use {@link ng.directive:ngModel.NgModelController - * NgModelController} exposed by this directive. - * - * `ngModel` is responsible for: - * - * - binding the view into the model, which other directives such as `input`, `textarea` or `select` - * require, - * - providing validation behavior (i.e. required, number, email, url), - * - keeping state of the control (valid/invalid, dirty/pristine, validation errors), - * - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`), - * - register the control with parent {@link ng.directive:form form}. - * - * Note: `ngModel` will try to bind to the property given by evaluating the expression on the - * current scope. If the property doesn't already exist on this scope, it will be created - * implicitly and added to the scope. - * - * For basic examples, how to use `ngModel`, see: - * - * - {@link ng.directive:input input} - * - {@link ng.directive:input.text text} - * - {@link ng.directive:input.checkbox checkbox} - * - {@link ng.directive:input.radio radio} - * - {@link ng.directive:input.number number} - * - {@link ng.directive:input.email email} - * - {@link ng.directive:input.url url} - * - {@link ng.directive:select select} - * - {@link ng.directive:textarea textarea} - * - */ -var ngModelDirective = function() { - return { - require: ['ngModel', '^?form'], - controller: NgModelController, - link: function(scope, element, attr, ctrls) { - // notify others, especially parent forms - - var modelCtrl = ctrls[0], - formCtrl = ctrls[1] || nullFormCtrl; - - formCtrl.$addControl(modelCtrl); - - element.on('$destroy', function() { - formCtrl.$removeControl(modelCtrl); - }); - } - }; -}; - - -/** - * @ngdoc directive - * @name ng.directive:ngChange - * @restrict E - * - * @description - * Evaluate given expression when user changes the input. - * The expression is not evaluated when the value change is coming from the model. - * - * Note, this directive requires `ngModel` to be present. - * - * @element input - * - * @example - * - * - * - *
- * - * - *
- * debug = {{confirmed}}
- * counter = {{counter}} - *
- *
- * - * it('should evaluate the expression if changing from view', function() { - * expect(binding('counter')).toEqual('0'); - * element('#ng-change-example1').click(); - * expect(binding('counter')).toEqual('1'); - * expect(binding('confirmed')).toEqual('true'); - * }); - * - * it('should not evaluate the expression if changing from model', function() { - * element('#ng-change-example2').click(); - * expect(binding('counter')).toEqual('0'); - * expect(binding('confirmed')).toEqual('true'); - * }); - * - *
- */ -var ngChangeDirective = valueFn({ - require: 'ngModel', - link: function(scope, element, attr, ctrl) { - ctrl.$viewChangeListeners.push(function() { - scope.$eval(attr.ngChange); - }); - } -}); - - -var requiredDirective = function() { - return { - require: '?ngModel', - link: function(scope, elm, attr, ctrl) { - if (!ctrl) return; - attr.required = true; // force truthy in case we are on non input element - - var validator = function(value) { - if (attr.required && (isEmpty(value) || value === false)) { - ctrl.$setValidity('required', false); - return; - } else { - ctrl.$setValidity('required', true); - return value; - } - }; - - ctrl.$formatters.push(validator); - ctrl.$parsers.unshift(validator); - - attr.$observe('required', function() { - validator(ctrl.$viewValue); - }); - } - }; -}; - - -/** - * @ngdoc directive - * @name ng.directive:ngList - * - * @description - * Text input that converts between comma-separated string into an array of strings. - * - * @element input - * @param {string=} ngList optional delimiter that should be used to split the value. If - * specified in form `/something/` then the value will be converted into a regular expression. - * - * @example - - - -
- List: - - Required! -
- names = {{names}}
- myForm.namesInput.$valid = {{myForm.namesInput.$valid}}
- myForm.namesInput.$error = {{myForm.namesInput.$error}}
- myForm.$valid = {{myForm.$valid}}
- myForm.$error.required = {{!!myForm.$error.required}}
-
-
- - it('should initialize to model', function() { - expect(binding('names')).toEqual('["igor","misko","vojta"]'); - expect(binding('myForm.namesInput.$valid')).toEqual('true'); - expect(element('span.error').css('display')).toBe('none'); - }); - - it('should be invalid if empty', function() { - input('names').enter(''); - expect(binding('names')).toEqual('[]'); - expect(binding('myForm.namesInput.$valid')).toEqual('false'); - expect(element('span.error').css('display')).not().toBe('none'); - }); - -
- */ -var ngListDirective = function() { - return { - require: 'ngModel', - link: function(scope, element, attr, ctrl) { - var match = /\/(.*)\//.exec(attr.ngList), - separator = match && new RegExp(match[1]) || attr.ngList || ','; - - var parse = function(viewValue) { - var list = []; - - if (viewValue) { - forEach(viewValue.split(separator), function(value) { - if (value) list.push(trim(value)); - }); - } - - return list; - }; - - ctrl.$parsers.push(parse); - ctrl.$formatters.push(function(value) { - if (isArray(value)) { - return value.join(', '); - } - - return undefined; - }); - } - }; -}; - - -var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; - -var ngValueDirective = function() { - return { - priority: 100, - compile: function(tpl, tplAttr) { - if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { - return function(scope, elm, attr) { - attr.$set('value', scope.$eval(attr.ngValue)); - }; - } else { - return function(scope, elm, attr) { - scope.$watch(attr.ngValue, function valueWatchAction(value) { - attr.$set('value', value); - }); - }; - } - } - }; -}; - -/** - * @ngdoc directive - * @name ng.directive:ngBind - * - * @description - * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element - * with the value of a given expression, and to update the text content when the value of that - * expression changes. - * - * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like - * `{{ expression }}` which is similar but less verbose. - * - * It is preferrable to use `ngBind` instead of `{{ expression }}` when a template is momentarily - * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an - * element attribute, it makes the bindings invisible to the user while the page is loading. - * - * An alternative solution to this problem would be using the - * {@link ng.directive:ngCloak ngCloak} directive. - * - * - * @element ANY - * @param {expression} ngBind {@link guide/expression Expression} to evaluate. - * - * @example - * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. - - - -
- Enter name:
- Hello ! -
-
- - it('should check ng-bind', function() { - expect(using('.doc-example-live').binding('name')).toBe('Whirled'); - using('.doc-example-live').input('name').enter('world'); - expect(using('.doc-example-live').binding('name')).toBe('world'); - }); - -
- */ -var ngBindDirective = ngDirective(function(scope, element, attr) { - element.addClass('ng-binding').data('$binding', attr.ngBind); - scope.$watch(attr.ngBind, function ngBindWatchAction(value) { - element.text(value == undefined ? '' : value); - }); -}); - - -/** - * @ngdoc directive - * @name ng.directive:ngBindTemplate - * - * @description - * The `ngBindTemplate` directive specifies that the element - * text content should be replaced with the interpolation of the template - * in the `ngBindTemplate` attribute. - * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` - * expressions. This directive is needed since some HTML elements - * (such as TITLE and OPTION) cannot contain SPAN elements. - * - * @element ANY - * @param {string} ngBindTemplate template of form - * {{ expression }} to eval. - * - * @example - * Try it here: enter text in text box and watch the greeting change. - - - -
- Salutation:
- Name:
-

-       
-
- - it('should check ng-bind', function() { - expect(using('.doc-example-live').binding('salutation')). - toBe('Hello'); - expect(using('.doc-example-live').binding('name')). - toBe('World'); - using('.doc-example-live').input('salutation').enter('Greetings'); - using('.doc-example-live').input('name').enter('user'); - expect(using('.doc-example-live').binding('salutation')). - toBe('Greetings'); - expect(using('.doc-example-live').binding('name')). - toBe('user'); - }); - -
- */ -var ngBindTemplateDirective = ['$interpolate', function($interpolate) { - return function(scope, element, attr) { - // TODO: move this to scenario runner - var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); - element.addClass('ng-binding').data('$binding', interpolateFn); - attr.$observe('ngBindTemplate', function(value) { - element.text(value); - }); - } -}]; - - -/** - * @ngdoc directive - * @name ng.directive:ngBindHtml - * - * @description - * Creates a binding that will innerHTML the result of evaluating the `expression` into the current - * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link - * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize` - * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in - * core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to - * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example - * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}. - * - * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you - * will have an exception (instead of an exploit.) - * - * @element ANY - * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. - */ -var ngBindHtmlDirective = ['$sce', function($sce) { - return function(scope, element, attr) { - element.addClass('ng-binding').data('$binding', attr.ngBindHtml); - scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function ngBindHtmlWatchAction(value) { - element.html(value || ''); - }); - }; -}]; - -function classDirective(name, selector) { - name = 'ngClass' + name; - return function() { - return { - restrict: 'AC', - link: function(scope, element, attr) { - var oldVal = undefined; - - scope.$watch(attr[name], ngClassWatchAction, true); - - attr.$observe('class', function(value) { - ngClassWatchAction(scope.$eval(attr[name])); - }); - - - if (name !== 'ngClass') { - scope.$watch('$index', function($index, old$index) { - var mod = $index & 1; - if (mod !== old$index & 1) { - if (mod === selector) { - addClass(scope.$eval(attr[name])); - } else { - removeClass(scope.$eval(attr[name])); - } - } - }); - } - - - function ngClassWatchAction(newVal) { - if (selector === true || scope.$index % 2 === selector) { - if (oldVal && !equals(newVal,oldVal)) { - removeClass(oldVal); - } - addClass(newVal); - } - oldVal = copy(newVal); - } - - - function removeClass(classVal) { - attr.$removeClass(flattenClasses(classVal)); - } - - - function addClass(classVal) { - attr.$addClass(flattenClasses(classVal)); - } - - function flattenClasses(classVal) { - if(isArray(classVal)) { - return classVal.join(' '); - } else if (isObject(classVal)) { - var classes = [], i = 0; - forEach(classVal, function(v, k) { - if (v) { - classes.push(k); - } - }); - return classes.join(' '); - } - - return classVal; - }; - } - }; - }; -} - -/** - * @ngdoc directive - * @name ng.directive:ngClass - * - * @description - * The `ngClass` allows you to set CSS classes on HTML an element, dynamically, by databinding - * an expression that represents all classes to be added. - * - * The directive won't add duplicate classes if a particular class was already set. - * - * When the expression changes, the previously added classes are removed and only then the - * new classes are added. - * - * @animations - * add - happens just before the class is applied to the element - * remove - happens just before the class is removed from the element - * - * @element ANY - * @param {expression} ngClass {@link guide/expression Expression} to eval. The result - * of the evaluation can be a string representing space delimited class - * names, an array, or a map of class names to boolean values. In the case of a map, the - * names of the properties whose values are truthy will be added as css classes to the - * element. - * - * @example Example that demostrates basic bindings via ngClass directive. - - -

Map Syntax Example

- bold - strike - red -
-

Using String Syntax

- -
-

Using Array Syntax

-
-
-
-
- - .strike { - text-decoration: line-through; - } - .bold { - font-weight: bold; - } - .red { - color: red; - } - - - it('should let you toggle the class', function() { - - expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/bold/); - expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/red/); - - input('bold').check(); - expect(element('.doc-example-live p:first').prop('className')).toMatch(/bold/); - - input('red').check(); - expect(element('.doc-example-live p:first').prop('className')).toMatch(/red/); - }); - - it('should let you toggle string example', function() { - expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe(''); - input('style').enter('red'); - expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe('red'); - }); - - it('array example should have 3 classes', function() { - expect(element('.doc-example-live p:last').prop('className')).toBe(''); - input('style1').enter('bold'); - input('style2').enter('strike'); - input('style3').enter('red'); - expect(element('.doc-example-live p:last').prop('className')).toBe('bold strike red'); - }); - -
- - ## Animations - - Example that demostrates how addition and removal of classes can be animated. - - - - - -
- Sample Text -
- - .my-class-add, .my-class-remove { - -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - } - - .my-class, - .my-class-add.my-class-add-active { - color: red; - font-size:3em; - } - - .my-class-remove.my-class-remove-active { - font-size:1.0em; - color:black; - } - - - it('should check ng-class', function() { - expect(element('.doc-example-live span').prop('className')).not(). - toMatch(/my-class/); - - using('.doc-example-live').element(':button:first').click(); - - expect(element('.doc-example-live span').prop('className')). - toMatch(/my-class/); - - using('.doc-example-live').element(':button:last').click(); - - expect(element('.doc-example-live span').prop('className')).not(). - toMatch(/my-class/); - }); - -
- */ -var ngClassDirective = classDirective('', true); - -/** - * @ngdoc directive - * @name ng.directive:ngClassOdd - * - * @description - * The `ngClassOdd` and `ngClassEven` directives work exactly as - * {@link ng.directive:ngClass ngClass}, except it works in - * conjunction with `ngRepeat` and takes affect only on odd (even) rows. - * - * This directive can be applied only within a scope of an - * {@link ng.directive:ngRepeat ngRepeat}. - * - * @element ANY - * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result - * of the evaluation can be a string representing space delimited class names or an array. - * - * @example - - -
    -
  1. - - {{name}} - -
  2. -
-
- - .odd { - color: red; - } - .even { - color: blue; - } - - - it('should check ng-class-odd and ng-class-even', function() { - expect(element('.doc-example-live li:first span').prop('className')). - toMatch(/odd/); - expect(element('.doc-example-live li:last span').prop('className')). - toMatch(/even/); - }); - -
- */ -var ngClassOddDirective = classDirective('Odd', 0); - -/** - * @ngdoc directive - * @name ng.directive:ngClassEven - * - * @description - * The `ngClassOdd` and `ngClassEven` directives work exactly as - * {@link ng.directive:ngClass ngClass}, except it works in - * conjunction with `ngRepeat` and takes affect only on odd (even) rows. - * - * This directive can be applied only within a scope of an - * {@link ng.directive:ngRepeat ngRepeat}. - * - * @element ANY - * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The - * result of the evaluation can be a string representing space delimited class names or an array. - * - * @example - - -
    -
  1. - - {{name}}       - -
  2. -
-
- - .odd { - color: red; - } - .even { - color: blue; - } - - - it('should check ng-class-odd and ng-class-even', function() { - expect(element('.doc-example-live li:first span').prop('className')). - toMatch(/odd/); - expect(element('.doc-example-live li:last span').prop('className')). - toMatch(/even/); - }); - -
- */ -var ngClassEvenDirective = classDirective('Even', 1); - -/** - * @ngdoc directive - * @name ng.directive:ngCloak - * - * @description - * The `ngCloak` directive is used to prevent the Angular html template from being briefly - * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this - * directive to avoid the undesirable flicker effect caused by the html template display. - * - * The directive can be applied to the `` element, but typically a fine-grained application is - * preferred in order to benefit from progressive rendering of the browser view. - * - * `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and - * `angular.min.js` files. Following is the css rule: - * - *
- * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
- *   display: none !important;
- * }
- * 
- * - * When this css rule is loaded by the browser, all html elements (including their children) that - * are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive - * during the compilation of the template it deletes the `ngCloak` element attribute, which - * makes the compiled element visible. - * - * For the best result, `angular.js` script must be loaded in the head section of the html file; - * alternatively, the css rule (above) must be included in the external stylesheet of the - * application. - * - * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they - * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css - * class `ngCloak` in addition to `ngCloak` directive as shown in the example below. - * - * @element ANY - * - * @example - - -
{{ 'hello' }}
-
{{ 'hello IE7' }}
-
- - it('should remove the template directive and css class', function() { - expect(element('.doc-example-live #template1').attr('ng-cloak')). - not().toBeDefined(); - expect(element('.doc-example-live #template2').attr('ng-cloak')). - not().toBeDefined(); - }); - -
- * - */ -var ngCloakDirective = ngDirective({ - compile: function(element, attr) { - attr.$set('ngCloak', undefined); - element.removeClass('ng-cloak'); - } -}); - -/** - * @ngdoc directive - * @name ng.directive:ngController - * - * @description - * The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular - * supports the principles behind the Model-View-Controller design pattern. - * - * MVC components in angular: - * - * * Model — The Model is data in scope properties; scopes are attached to the DOM. - * * View — The template (HTML with data bindings) is rendered into the View. - * * Controller — The `ngController` directive specifies a Controller class; the class has - * methods that typically express the business logic behind the application. - * - * Note that an alternative way to define controllers is via the {@link ngRoute.$route $route} service. - * - * @element ANY - * @scope - * @param {expression} ngController Name of a globally accessible constructor function or an - * {@link guide/expression expression} that on the current scope evaluates to a - * constructor function. The controller instance can further be published into the scope - * by adding `as localName` the controller name attribute. - * - * @example - * Here is a simple form for editing user contact information. Adding, removing, clearing, and - * greeting are methods declared on the controller (see source tab). These methods can - * easily be called from the angular markup. Notice that the scope becomes the `this` for the - * controller's instance. This allows for easy access to the view data from the controller. Also - * notice that any changes to the data are automatically reflected in the View without the need - * for a manual update. The example is included in two different declaration styles based on - * your style preferences. - - - -
- Name: - [ greet ]
- Contact: -
    -
  • - - - [ clear - | X ] -
  • -
  • [ add ]
  • -
-
-
- - it('should check controller as', function() { - expect(element('#ctrl-as-exmpl>:input').val()).toBe('John Smith'); - expect(element('#ctrl-as-exmpl li:nth-child(1) input').val()) - .toBe('408 555 1212'); - expect(element('#ctrl-as-exmpl li:nth-child(2) input').val()) - .toBe('john.smith@example.org'); - - element('#ctrl-as-exmpl li:first a:contains("clear")').click(); - expect(element('#ctrl-as-exmpl li:first input').val()).toBe(''); - - element('#ctrl-as-exmpl li:last a:contains("add")').click(); - expect(element('#ctrl-as-exmpl li:nth-child(3) input').val()) - .toBe('yourname@example.org'); - }); - -
- - - -
- Name: - [ greet ]
- Contact: -
    -
  • - - - [ clear - | X ] -
  • -
  • [ add ]
  • -
-
-
- - it('should check controller', function() { - expect(element('#ctrl-exmpl>:input').val()).toBe('John Smith'); - expect(element('#ctrl-exmpl li:nth-child(1) input').val()) - .toBe('408 555 1212'); - expect(element('#ctrl-exmpl li:nth-child(2) input').val()) - .toBe('john.smith@example.org'); - - element('#ctrl-exmpl li:first a:contains("clear")').click(); - expect(element('#ctrl-exmpl li:first input').val()).toBe(''); - - element('#ctrl-exmpl li:last a:contains("add")').click(); - expect(element('#ctrl-exmpl li:nth-child(3) input').val()) - .toBe('yourname@example.org'); - }); - -
- - */ -var ngControllerDirective = [function() { - return { - scope: true, - controller: '@' - }; -}]; - -/** - * @ngdoc directive - * @name ng.directive:ngCsp - * @priority 1000 - * - * @element html - * @description - * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. - * - * This is necessary when developing things like Google Chrome Extensions. - * - * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things). - * For us to be compatible, we just need to implement the "getterFn" in $parse without violating - * any of these restrictions. - * - * AngularJS uses `Function(string)` generated functions as a speed optimization. By applying `ngCsp` - * it is be possible to opt into the CSP compatible mode. When this mode is on AngularJS will - * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will - * be raised. - * - * In order to use this feature put `ngCsp` directive on the root element of the application. - * - * @example - * This example shows how to apply the `ngCsp` directive to the `html` tag. -
-     
-     
-     ...
-     ...
-     
-   
- */ - -var ngCspDirective = ['$sniffer', function($sniffer) { - return { - priority: 1000, - compile: function() { - $sniffer.csp = true; - } - }; -}]; - -/** - * @ngdoc directive - * @name ng.directive:ngClick - * - * @description - * The ngClick allows you to specify custom behavior when - * element is clicked. - * - * @element ANY - * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon - * click. (Event object is available as `$event`) - * - * @example - - - - count: {{count}} - - - it('should check ng-click', function() { - expect(binding('count')).toBe('0'); - element('.doc-example-live :button').click(); - expect(binding('count')).toBe('1'); - }); - - - */ -/* - * A directive that allows creation of custom onclick handlers that are defined as angular - * expressions and are compiled and executed within the current scope. - * - * Events that are handled via these handler are always configured not to propagate further. - */ -var ngEventDirectives = {}; -forEach( - 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur'.split(' '), - function(name) { - var directiveName = directiveNormalize('ng-' + name); - ngEventDirectives[directiveName] = ['$parse', function($parse) { - return function(scope, element, attr) { - var fn = $parse(attr[directiveName]); - element.on(lowercase(name), function(event) { - scope.$apply(function() { - fn(scope, {$event:event}); - }); - }); - }; - }]; - } -); - -/** - * @ngdoc directive - * @name ng.directive:ngDblclick - * - * @description - * The `ngDblclick` directive allows you to specify custom behavior on dblclick event. - * - * @element ANY - * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon - * dblclick. (Event object is available as `$event`) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - - -/** - * @ngdoc directive - * @name ng.directive:ngMousedown - * - * @description - * The ngMousedown directive allows you to specify custom behavior on mousedown event. - * - * @element ANY - * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon - * mousedown. (Event object is available as `$event`) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - - -/** - * @ngdoc directive - * @name ng.directive:ngMouseup - * - * @description - * Specify custom behavior on mouseup event. - * - * @element ANY - * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon - * mouseup. (Event object is available as `$event`) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - -/** - * @ngdoc directive - * @name ng.directive:ngMouseover - * - * @description - * Specify custom behavior on mouseover event. - * - * @element ANY - * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon - * mouseover. (Event object is available as `$event`) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - - -/** - * @ngdoc directive - * @name ng.directive:ngMouseenter - * - * @description - * Specify custom behavior on mouseenter event. - * - * @element ANY - * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon - * mouseenter. (Event object is available as `$event`) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - - -/** - * @ngdoc directive - * @name ng.directive:ngMouseleave - * - * @description - * Specify custom behavior on mouseleave event. - * - * @element ANY - * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon - * mouseleave. (Event object is available as `$event`) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - - -/** - * @ngdoc directive - * @name ng.directive:ngMousemove - * - * @description - * Specify custom behavior on mousemove event. - * - * @element ANY - * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon - * mousemove. (Event object is available as `$event`) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - - -/** - * @ngdoc directive - * @name ng.directive:ngKeydown - * - * @description - * Specify custom behavior on keydown event. - * - * @element ANY - * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon - * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - - -/** - * @ngdoc directive - * @name ng.directive:ngKeyup - * - * @description - * Specify custom behavior on keyup event. - * - * @element ANY - * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon - * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - - -/** - * @ngdoc directive - * @name ng.directive:ngKeypress - * - * @description - * Specify custom behavior on keypress event. - * - * @element ANY - * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon - * keypress. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - - -/** - * @ngdoc directive - * @name ng.directive:ngSubmit - * - * @description - * Enables binding angular expressions to onsubmit events. - * - * Additionally it prevents the default action (which for form means sending the request to the - * server and reloading the current page) **but only if the form does not contain an `action` - * attribute**. - * - * @element form - * @param {expression} ngSubmit {@link guide/expression Expression} to eval. (Event object is available as `$event`) - * - * @example - - - -
- Enter text and hit enter: - - -
list={{list}}
-
-
- - it('should check ng-submit', function() { - expect(binding('list')).toBe('[]'); - element('.doc-example-live #submit').click(); - expect(binding('list')).toBe('["hello"]'); - expect(input('text').val()).toBe(''); - }); - it('should ignore empty strings', function() { - expect(binding('list')).toBe('[]'); - element('.doc-example-live #submit').click(); - element('.doc-example-live #submit').click(); - expect(binding('list')).toBe('["hello"]'); - }); - -
- */ - -/** - * @ngdoc directive - * @name ng.directive:ngFocus - * - * @description - * Specify custom behavior on focus event. - * - * @element window, input, select, textarea, a - * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon - * focus. (Event object is available as `$event`) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - -/** - * @ngdoc directive - * @name ng.directive:ngBlur - * - * @description - * Specify custom behavior on blur event. - * - * @element window, input, select, textarea, a - * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon - * blur. (Event object is available as `$event`) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - -/** - * @ngdoc directive - * @name ng.directive:ngIf - * @restrict A - * - * @description - * The `ngIf` directive removes and recreates a portion of the DOM tree (HTML) - * conditionally based on **"falsy"** and **"truthy"** values, respectively, evaluated within - * an {expression}. In other words, if the expression assigned to **ngIf evaluates to a false - * value** then **the element is removed from the DOM** and **if true** then **a clone of the - * element is reinserted into the DOM**. - * - * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the - * element in the DOM rather than changing its visibility via the `display` css property. A common - * case when this difference is significant is when using css selectors that rely on an element's - * position within the DOM (HTML), such as the `:first-child` or `:last-child` pseudo-classes. - * - * Note that **when an element is removed using ngIf its scope is destroyed** and **a new scope - * is created when the element is restored**. The scope created within `ngIf` inherits from - * its parent scope using - * {@link https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance prototypal inheritance}. - * An important implication of this is if `ngModel` is used within `ngIf` to bind to - * a javascript primitive defined in the parent scope. In this case any modifications made to the - * variable within the child scope will override (hide) the value in the parent scope. - * - * Also, `ngIf` recreates elements using their compiled state. An example scenario of this behavior - * is if an element's class attribute is directly modified after it's compiled, using something like - * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element - * the added class will be lost because the original compiled state is used to regenerate the element. - * - * Additionally, you can provide animations via the ngAnimate module to animate the **enter** - * and **leave** effects. - * - * @animations - * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container - * leave - happens just before the ngIf contents are removed from the DOM - * - * @element ANY - * @scope - * @param {expression} ngIf If the {@link guide/expression expression} is falsy then - * the element is removed from the DOM tree (HTML). - * - * @example - - - Click me:
- Show when checked: - - I'm removed when the checkbox is unchecked. - -
- - .animate-if { - background:white; - border:1px solid black; - padding:10px; - } - - .animate-if.ng-enter, .animate-if.ng-leave { - -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - } - - .animate-if.ng-enter, - .animate-if.ng-leave.ng-leave-active { - opacity:0; - } - - .animate-if.ng-enter.ng-enter-active, - .animate-if.ng-leave { - opacity:1; - } - -
- */ -var ngIfDirective = ['$animate', function($animate) { - return { - transclude: 'element', - priority: 1000, - terminal: true, - restrict: 'A', - compile: function (element, attr, transclude) { - return function ($scope, $element, $attr) { - var childElement, childScope; - $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { - if (childElement) { - $animate.leave(childElement); - childElement = undefined; - } - if (childScope) { - childScope.$destroy(); - childScope = undefined; - } - if (toBoolean(value)) { - childScope = $scope.$new(); - transclude(childScope, function (clone) { - childElement = clone; - $animate.enter(clone, $element.parent(), $element); - }); - } - }); - } - } - } -}]; - -/** - * @ngdoc directive - * @name ng.directive:ngInclude - * @restrict ECA - * - * @description - * Fetches, compiles and includes an external HTML fragment. - * - * Keep in mind that: - * - * - by default, the template URL is restricted to the same domain and protocol as the - * application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl - * $sce.getTrustedResourceUrl} on it. To load templates from other domains and/or protocols, - * you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or - * {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. Refer Angular's {@link - * ng.$sce Strict Contextual Escaping}. - * - in addition, the browser's - * {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest - * Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing - * (CORS)} policy apply that may further restrict whether the template is successfully loaded. - * (e.g. ngInclude won't work for cross-domain requests on all browsers and for `file://` - * access on some browsers) - * - * @animations - * enter - animation is used to bring new content into the browser. - * leave - animation is used to animate existing content away. - * - * The enter and leave animation occur concurrently. - * - * @scope - * - * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, - * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`. - * @param {string=} onload Expression to evaluate when a new partial is loaded. - * - * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll - * $anchorScroll} to scroll the viewport after the content is loaded. - * - * - If the attribute is not set, disable scrolling. - * - If the attribute is set without value, enable scrolling. - * - Otherwise enable scrolling only if the expression evaluates to truthy value. - * - * @example - - -
- - url of the template: {{template.url}} -
-
-
-
-
-
- - function Ctrl($scope) { - $scope.templates = - [ { name: 'template1.html', url: 'template1.html'} - , { name: 'template2.html', url: 'template2.html'} ]; - $scope.template = $scope.templates[0]; - } - - - Content of template1.html - - - Content of template2.html - - - .example-animate-container { - position:relative; - background:white; - border:1px solid black; - height:40px; - overflow:hidden; - } - - .example-animate-container > div { - padding:10px; - } - - .include-example.ng-enter, .include-example.ng-leave { - -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - - position:absolute; - top:0; - left:0; - right:0; - bottom:0; - display:block; - padding:10px; - } - - .include-example.ng-enter { - top:-50px; - } - .include-example.ng-enter.ng-enter-active { - top:0; - } - - .include-example.ng-leave { - top:0; - } - .include-example.ng-leave.ng-leave-active { - top:50px; - } - - - it('should load template1.html', function() { - expect(element('.doc-example-live [ng-include]').text()). - toMatch(/Content of template1.html/); - }); - it('should load template2.html', function() { - select('template').option('1'); - expect(element('.doc-example-live [ng-include]').text()). - toMatch(/Content of template2.html/); - }); - it('should change to blank', function() { - select('template').option(''); - expect(element('.doc-example-live [ng-include]')).toBe(undefined); - }); - -
- */ - - -/** - * @ngdoc event - * @name ng.directive:ngInclude#$includeContentRequested - * @eventOf ng.directive:ngInclude - * @eventType emit on the scope ngInclude was declared in - * @description - * Emitted every time the ngInclude content is requested. - */ - - -/** - * @ngdoc event - * @name ng.directive:ngInclude#$includeContentLoaded - * @eventOf ng.directive:ngInclude - * @eventType emit on the current ngInclude scope - * @description - * Emitted every time the ngInclude content is reloaded. - */ -var NG_INCLUDE_PRIORITY = 500; -var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', '$animate', '$sce', - function($http, $templateCache, $anchorScroll, $compile, $animate, $sce) { - return { - restrict: 'ECA', - terminal: true, - priority: NG_INCLUDE_PRIORITY, - compile: function(element, attr) { - var srcExp = attr.ngInclude || attr.src, - onloadExp = attr.onload || '', - autoScrollExp = attr.autoscroll; - - element.html(''); - var anchor = jqLite(document.createComment(' ngInclude: ' + srcExp + ' ')); - element.replaceWith(anchor); - - return function(scope) { - var changeCounter = 0, - currentScope, - currentElement; - - var cleanupLastIncludeContent = function() { - if (currentScope) { - currentScope.$destroy(); - currentScope = null; - } - if(currentElement) { - $animate.leave(currentElement); - currentElement = null; - } - }; - - scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) { - var thisChangeId = ++changeCounter; - - if (src) { - $http.get(src, {cache: $templateCache}).success(function(response) { - if (thisChangeId !== changeCounter) return; - var newScope = scope.$new(); - - cleanupLastIncludeContent(); - - currentScope = newScope; - currentElement = element.clone(); - currentElement.html(response); - $animate.enter(currentElement, null, anchor); - - $compile(currentElement, false, NG_INCLUDE_PRIORITY - 1)(currentScope); - - if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { - $anchorScroll(); - } - - currentScope.$emit('$includeContentLoaded'); - scope.$eval(onloadExp); - }).error(function() { - if (thisChangeId === changeCounter) cleanupLastIncludeContent(); - }); - scope.$emit('$includeContentRequested'); - } else { - cleanupLastIncludeContent(); - } - }); - }; - } - }; -}]; - -/** - * @ngdoc directive - * @name ng.directive:ngInit - * - * @description - * The `ngInit` directive specifies initialization tasks to be executed - * before the template enters execution mode during bootstrap. - * - * @element ANY - * @param {expression} ngInit {@link guide/expression Expression} to eval. - * - * @example - - -
- {{greeting}} {{person}}! -
-
- - it('should check greeting', function() { - expect(binding('greeting')).toBe('Hello'); - expect(binding('person')).toBe('World'); - }); - -
- */ -var ngInitDirective = ngDirective({ - compile: function() { - return { - pre: function(scope, element, attrs) { - scope.$eval(attrs.ngInit); - } - } - } -}); - -/** - * @ngdoc directive - * @name ng.directive:ngNonBindable - * @priority 1000 - * - * @description - * Sometimes it is necessary to write code which looks like bindings but which should be left alone - * by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML. - * - * @element ANY - * - * @example - * In this example there are two location where a simple binding (`{{}}`) is present, but the one - * wrapped in `ngNonBindable` is left alone. - * - * @example - - -
Normal: {{1 + 2}}
-
Ignored: {{1 + 2}}
-
- - it('should check ng-non-bindable', function() { - expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); - expect(using('.doc-example-live').element('div:last').text()). - toMatch(/1 \+ 2/); - }); - -
- */ -var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); - -/** - * @ngdoc directive - * @name ng.directive:ngPluralize - * @restrict EA - * - * @description - * # Overview - * `ngPluralize` is a directive that displays messages according to en-US localization rules. - * These rules are bundled with angular.js, but can be overridden - * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive - * by specifying the mappings between - * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html - * plural categories} and the strings to be displayed. - * - * # Plural categories and explicit number rules - * There are two - * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html - * plural categories} in Angular's default en-US locale: "one" and "other". - * - * While a plural category may match many numbers (for example, in en-US locale, "other" can match - * any number that is not 1), an explicit number rule can only match one number. For example, the - * explicit number rule for "3" matches the number 3. There are examples of plural categories - * and explicit number rules throughout the rest of this documentation. - * - * # Configuring ngPluralize - * You configure ngPluralize by providing 2 attributes: `count` and `when`. - * You can also provide an optional attribute, `offset`. - * - * The value of the `count` attribute can be either a string or an {@link guide/expression - * Angular expression}; these are evaluated on the current scope for its bound value. - * - * The `when` attribute specifies the mappings between plural categories and the actual - * string to be displayed. The value of the attribute should be a JSON object. - * - * The following example shows how to configure ngPluralize: - * - *
- * 
- * 
- *
- * - * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not - * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" - * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for - * other numbers, for example 12, so that instead of showing "12 people are viewing", you can - * show "a dozen people are viewing". - * - * You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted - * into pluralized strings. In the previous example, Angular will replace `{}` with - * `{{personCount}}`. The closed braces `{}` is a placeholder - * for {{numberExpression}}. - * - * # Configuring ngPluralize with offset - * The `offset` attribute allows further customization of pluralized text, which can result in - * a better user experience. For example, instead of the message "4 people are viewing this document", - * you might display "John, Kate and 2 others are viewing this document". - * The offset attribute allows you to offset a number by any desired value. - * Let's take a look at an example: - * - *
- * 
- * 
- * 
- * - * Notice that we are still using two plural categories(one, other), but we added - * three explicit number rules 0, 1 and 2. - * When one person, perhaps John, views the document, "John is viewing" will be shown. - * When three people view the document, no explicit number rule is found, so - * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. - * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing" - * is shown. - * - * Note that when you specify offsets, you must provide explicit number rules for - * numbers from 0 up to and including the offset. If you use an offset of 3, for example, - * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for - * plural categories "one" and "other". - * - * @param {string|expression} count The variable to be bounded to. - * @param {string} when The mapping between plural category to its corresponding strings. - * @param {number=} offset Offset to deduct from the total number. - * - * @example - - - -
- Person 1:
- Person 2:
- Number of People:
- - - Without Offset: - -
- - - With Offset(2): - - -
-
- - it('should show correct pluralized string', function() { - expect(element('.doc-example-live ng-pluralize:first').text()). - toBe('1 person is viewing.'); - expect(element('.doc-example-live ng-pluralize:last').text()). - toBe('Igor is viewing.'); - - using('.doc-example-live').input('personCount').enter('0'); - expect(element('.doc-example-live ng-pluralize:first').text()). - toBe('Nobody is viewing.'); - expect(element('.doc-example-live ng-pluralize:last').text()). - toBe('Nobody is viewing.'); - - using('.doc-example-live').input('personCount').enter('2'); - expect(element('.doc-example-live ng-pluralize:first').text()). - toBe('2 people are viewing.'); - expect(element('.doc-example-live ng-pluralize:last').text()). - toBe('Igor and Misko are viewing.'); - - using('.doc-example-live').input('personCount').enter('3'); - expect(element('.doc-example-live ng-pluralize:first').text()). - toBe('3 people are viewing.'); - expect(element('.doc-example-live ng-pluralize:last').text()). - toBe('Igor, Misko and one other person are viewing.'); - - using('.doc-example-live').input('personCount').enter('4'); - expect(element('.doc-example-live ng-pluralize:first').text()). - toBe('4 people are viewing.'); - expect(element('.doc-example-live ng-pluralize:last').text()). - toBe('Igor, Misko and 2 other people are viewing.'); - }); - - it('should show data-binded names', function() { - using('.doc-example-live').input('personCount').enter('4'); - expect(element('.doc-example-live ng-pluralize:last').text()). - toBe('Igor, Misko and 2 other people are viewing.'); - - using('.doc-example-live').input('person1').enter('Di'); - using('.doc-example-live').input('person2').enter('Vojta'); - expect(element('.doc-example-live ng-pluralize:last').text()). - toBe('Di, Vojta and 2 other people are viewing.'); - }); - -
- */ -var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { - var BRACE = /{}/g; - return { - restrict: 'EA', - link: function(scope, element, attr) { - var numberExp = attr.count, - whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs - offset = attr.offset || 0, - whens = scope.$eval(whenExp) || {}, - whensExpFns = {}, - startSymbol = $interpolate.startSymbol(), - endSymbol = $interpolate.endSymbol(), - isWhen = /^when(Minus)?(.+)$/; - - forEach(attr, function(expression, attributeName) { - if (isWhen.test(attributeName)) { - whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] = - element.attr(attr.$attr[attributeName]); - } - }); - forEach(whens, function(expression, key) { - whensExpFns[key] = - $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' + - offset + endSymbol)); - }); - - scope.$watch(function ngPluralizeWatch() { - var value = parseFloat(scope.$eval(numberExp)); - - if (!isNaN(value)) { - //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, - //check it against pluralization rules in $locale service - if (!(value in whens)) value = $locale.pluralCat(value - offset); - return whensExpFns[value](scope, element, true); - } else { - return ''; - } - }, function ngPluralizeWatchAction(newVal) { - element.text(newVal); - }); - } - }; -}]; - -/** - * @ngdoc directive - * @name ng.directive:ngRepeat - * - * @description - * The `ngRepeat` directive instantiates a template once per item from a collection. Each template - * instance gets its own scope, where the given loop variable is set to the current collection item, - * and `$index` is set to the item index or key. - * - * Special properties are exposed on the local scope of each template instance, including: - * - * | Variable | Type | Details | - * |-----------|-----------------|-----------------------------------------------------------------------------| - * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) | - * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. | - * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. | - * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. | - * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). | - * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). | - * - * - * # Special repeat start and end points - * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending - * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively. - * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on) - * up to and including the ending HTML tag where **ng-repeat-end** is placed. - * - * The example below makes use of this feature: - *
- *   
- * Header {{ item }} - *
- *
- * Body {{ item }} - *
- *
- * Footer {{ item }} - *
- *
- * - * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to: - *
- *   
- * Header A - *
- *
- * Body A - *
- *
- * Footer A - *
- *
- * Header B - *
- *
- * Body B - *
- *
- * Footer B - *
- *
- * - * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such - * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**). - * - * @animations - * enter - when a new item is added to the list or when an item is revealed after a filter - * leave - when an item is removed from the list or when an item is filtered out - * move - when an adjacent item is filtered out causing a reorder or when the item contents are reordered - * - * @element ANY - * @scope - * @priority 1000 - * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These - * formats are currently supported: - * - * * `variable in expression` – where variable is the user defined loop variable and `expression` - * is a scope expression giving the collection to enumerate. - * - * For example: `album in artist.albums`. - * - * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, - * and `expression` is the scope expression giving the collection to enumerate. - * - * For example: `(name, age) in {'adam':10, 'amalie':12}`. - * - * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function - * which can be used to associate the objects in the collection with the DOM elements. If no tracking function - * is specified the ng-repeat associates elements by identity in the collection. It is an error to have - * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are - * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression, - * before specifying a tracking expression. - * - * For example: `item in items` is equivalent to `item in items track by $id(item)'. This implies that the DOM elements - * will be associated by item identity in the array. - * - * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique - * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements - * with the corresponding item in the array by identity. Moving the same object in array would move the DOM - * element in the same way ian the DOM. - * - * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this - * case the object identity does not matter. Two objects are considered equivalent as long as their `id` - * property is same. - * - * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter - * to items in conjunction with a tracking expression. - * - * @example - * This example initializes the scope to a list of names and - * then uses `ngRepeat` to display every person: - - -
- I have {{friends.length}} friends. They are: - -
    -
  • - [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. -
  • -
-
-
- - .example-animate-container { - background:white; - border:1px solid black; - list-style:none; - margin:0; - padding:0; - } - - .example-animate-container > li { - padding:10px; - list-style:none; - } - - .animate-repeat.ng-enter, - .animate-repeat.ng-leave, - .animate-repeat.ng-move { - -webkit-transition:all linear 0.5s; - -moz-transition:all linear 0.5s; - -o-transition:all linear 0.5s; - transition:all linear 0.5s; - } - - .animate-repeat.ng-enter { - line-height:0; - opacity:0; - padding-top:0; - padding-bottom:0; - } - .animate-repeat.ng-enter.ng-enter-active { - line-height:20px; - opacity:1; - padding:10px; - } - - .animate-repeat.ng-leave { - opacity:1; - line-height:20px; - padding:10px; - } - .animate-repeat.ng-leave.ng-leave-active { - opacity:0; - line-height:0; - padding-top:0; - padding-bottom:0; - } - - .animate-repeat.ng-move { } - .animate-repeat.ng-move.ng-move-active { } - - - it('should render initial data set', function() { - var r = using('.doc-example-live').repeater('ul li'); - expect(r.count()).toBe(10); - expect(r.row(0)).toEqual(["1","John","25"]); - expect(r.row(1)).toEqual(["2","Jessie","30"]); - expect(r.row(9)).toEqual(["10","Samantha","60"]); - expect(binding('friends.length')).toBe("10"); - }); - - it('should update repeater when filter predicate changes', function() { - var r = using('.doc-example-live').repeater('ul li'); - expect(r.count()).toBe(10); - - input('q').enter('ma'); - - expect(r.count()).toBe(2); - expect(r.row(0)).toEqual(["1","Mary","28"]); - expect(r.row(1)).toEqual(["2","Samantha","60"]); - }); - -
- */ -var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { - var NG_REMOVED = '$$NG_REMOVED'; - var ngRepeatMinErr = minErr('ngRepeat'); - return { - transclude: 'element', - priority: 1000, - terminal: true, - compile: function(element, attr, linker) { - return function($scope, $element, $attr){ - var expression = $attr.ngRepeat; - var match = expression.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/), - trackByExp, trackByExpGetter, trackByIdFn, trackByIdArrayFn, trackByIdObjFn, lhs, rhs, valueIdentifier, keyIdentifier, - hashFnLocals = {$id: hashKey}; - - if (!match) { - throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", - expression); - } - - lhs = match[1]; - rhs = match[2]; - trackByExp = match[4]; - - if (trackByExp) { - trackByExpGetter = $parse(trackByExp); - trackByIdFn = function(key, value, index) { - // assign key, value, and $index to the locals so that they can be used in hash functions - if (keyIdentifier) hashFnLocals[keyIdentifier] = key; - hashFnLocals[valueIdentifier] = value; - hashFnLocals.$index = index; - return trackByExpGetter($scope, hashFnLocals); - }; - } else { - trackByIdArrayFn = function(key, value) { - return hashKey(value); - } - trackByIdObjFn = function(key) { - return key; - } - } - - match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); - if (!match) { - throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.", - lhs); - } - valueIdentifier = match[3] || match[1]; - keyIdentifier = match[2]; - - // Store a list of elements from previous run. This is a hash where key is the item from the - // iterator, and the value is objects with following properties. - // - scope: bound scope - // - element: previous element. - // - index: position - var lastBlockMap = {}; - - //watch props - $scope.$watchCollection(rhs, function ngRepeatAction(collection){ - var index, length, - previousNode = $element[0], // current position of the node - nextNode, - // Same as lastBlockMap but it has the current state. It will become the - // lastBlockMap on the next iteration. - nextBlockMap = {}, - arrayLength, - childScope, - key, value, // key/value of iteration - trackById, - collectionKeys, - block, // last object information {scope, element, id} - nextBlockOrder = []; - - - if (isArrayLike(collection)) { - collectionKeys = collection; - trackByIdFn = trackByIdFn || trackByIdArrayFn; - } else { - trackByIdFn = trackByIdFn || trackByIdObjFn; - // if object, extract keys, sort them and use to determine order of iteration over obj props - collectionKeys = []; - for (key in collection) { - if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { - collectionKeys.push(key); - } - } - collectionKeys.sort(); - } - - arrayLength = collectionKeys.length; - - // locate existing items - length = nextBlockOrder.length = collectionKeys.length; - for(index = 0; index < length; index++) { - key = (collection === collectionKeys) ? index : collectionKeys[index]; - value = collection[key]; - trackById = trackByIdFn(key, value, index); - if(lastBlockMap.hasOwnProperty(trackById)) { - block = lastBlockMap[trackById] - delete lastBlockMap[trackById]; - nextBlockMap[trackById] = block; - nextBlockOrder[index] = block; - } else if (nextBlockMap.hasOwnProperty(trackById)) { - // restore lastBlockMap - forEach(nextBlockOrder, function(block) { - if (block && block.startNode) lastBlockMap[block.id] = block; - }); - // This is a duplicate and we need to throw an error - throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}", - expression, trackById); - } else { - // new never before seen block - nextBlockOrder[index] = { id: trackById }; - nextBlockMap[trackById] = false; - } - } - - // remove existing items - for (key in lastBlockMap) { - if (lastBlockMap.hasOwnProperty(key)) { - block = lastBlockMap[key]; - $animate.leave(block.elements); - forEach(block.elements, function(element) { element[NG_REMOVED] = true}); - block.scope.$destroy(); - } - } - - // we are not using forEach for perf reasons (trying to avoid #call) - for (index = 0, length = collectionKeys.length; index < length; index++) { - key = (collection === collectionKeys) ? index : collectionKeys[index]; - value = collection[key]; - block = nextBlockOrder[index]; - - if (block.startNode) { - // if we have already seen this object, then we need to reuse the - // associated scope/element - childScope = block.scope; - - nextNode = previousNode; - do { - nextNode = nextNode.nextSibling; - } while(nextNode && nextNode[NG_REMOVED]); - - if (block.startNode == nextNode) { - // do nothing - } else { - // existing item which got moved - $animate.move(block.elements, null, jqLite(previousNode)); - } - previousNode = block.endNode; - } else { - // new item which we don't know about - childScope = $scope.$new(); - } - - childScope[valueIdentifier] = value; - if (keyIdentifier) childScope[keyIdentifier] = key; - childScope.$index = index; - childScope.$first = (index === 0); - childScope.$last = (index === (arrayLength - 1)); - childScope.$middle = !(childScope.$first || childScope.$last); - childScope.$odd = !(childScope.$even = index%2==0); - - if (!block.startNode) { - linker(childScope, function(clone) { - $animate.enter(clone, null, jqLite(previousNode)); - previousNode = clone; - block.scope = childScope; - block.startNode = clone[0]; - block.elements = clone; - block.endNode = clone[clone.length - 1]; - nextBlockMap[block.id] = block; - }); - } - } - lastBlockMap = nextBlockMap; - }); - }; - } - }; -}]; - -/** - * @ngdoc directive - * @name ng.directive:ngShow - * - * @description - * The `ngShow` directive shows and hides the given HTML element conditionally based on the expression - * provided to the ngShow attribute. The show and hide mechanism is a achieved by removing and adding - * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is a predefined CSS class present - * in AngularJS which sets the display style to none (using an !important flag). - * - *
- * 
- * 
- * - * - *
- *
- * - * When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute - * on the element causing it to become hidden. When true, the ng-hide CSS class is removed - * from the element causing the element not to appear hidden. - * - * ## Why is !important used? - * - * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector - * can be easily overridden by heavier selectors. For example, something as simple - * as changing the display style on a HTML list item would make hidden elements appear visible. - * This also becomes a bigger issue when dealing with CSS frameworks. - * - * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector - * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the - * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. - * - * ### Overriding .ng-hide - * - * If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by - * restating the styles for the .ng-hide class in CSS: - *
- * .ng-hide {
- *   //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
- *   display:block!important;
- *
- *   //this is just another form of hiding an element
- *   position:absolute;
- *   top:-9999px;
- *   left:-9999px;
- * }
- * 
- * - * Just remember to include the important flag so the CSS override will function. - * - * ## A note about animations with ngShow - * - * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression - * is true and false. This system works similar to the animation system present with ngClass, however, the - * only difference is that you must also include the !important flag to override the display property so - * that you can perform an animation when the element is hidden during the time of the animation. - * - *
- * //
- * //a working example can be found at the bottom of this page
- * //
- * .my-element.ng-hide-add, .my-element.ng-hide-remove {
- *   transition:0.5s linear all;
- *   display:block!important;
- * }
- *
- * .my-element.ng-hide-add { ... }
- * .my-element.ng-hide-add.ng-hide-add-active { ... }
- * .my-element.ng-hide-remove { ... }
- * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
- * 
- * - * @animations - * addClass: .ng-hide - happens after the ngShow expression evaluates to a truthy value and the just before contents are set to visible - * removeClass: .ng-hide - happens after the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden - * - * @element ANY - * @param {expression} ngShow If the {@link guide/expression expression} is truthy - * then the element is shown or hidden respectively. - * - * @example - - - Click me:
-
- Show: -
- I show up when your checkbox is checked. -
-
-
- Hide: -
- I hide when your checkbox is checked. -
-
-
- - .animate-show.ng-hide-add, - .animate-show.ng-hide-remove { - -webkit-transition:all linear 0.5s; - -moz-transition:all linear 0.5s; - -o-transition:all linear 0.5s; - transition:all linear 0.5s; - display:block!important; - } - - .animate-show.ng-hide-add.ng-hide-add-active, - .animate-show.ng-hide-remove { - line-height:0; - opacity:0; - padding:0 10px; - } - - .animate-show.ng-hide-add, - .animate-show.ng-hide-remove.ng-hide-remove-active { - line-height:20px; - opacity:1; - padding:10px; - border:1px solid black; - background:white; - } - - .check-element { - padding:10px; - border:1px solid black; - background:white; - } - - - it('should check ng-show / ng-hide', function() { - expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); - expect(element('.doc-example-live span:last:visible').count()).toEqual(1); - - input('checked').check(); - - expect(element('.doc-example-live span:first:visible').count()).toEqual(1); - expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); - }); - -
- */ -var ngShowDirective = ['$animate', function($animate) { - return function(scope, element, attr) { - scope.$watch(attr.ngShow, function ngShowWatchAction(value){ - $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide'); - }); - }; -}]; - - -/** - * @ngdoc directive - * @name ng.directive:ngHide - * - * @description - * The `ngHide` directive shows and hides the given HTML element conditionally based on the expression - * provided to the ngHide attribute. The show and hide mechanism is a achieved by removing and adding - * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is a predefined CSS class present - * in AngularJS which sets the display style to none (using an !important flag). - * - *
- * 
- * 
- * - * - *
- *
- * - * When the ngHide expression evaluates to true then the .ng-hide CSS class is added to the class attribute - * on the element causing it to become hidden. When false, the ng-hide CSS class is removed - * from the element causing the element not to appear hidden. - * - * ## Why is !important used? - * - * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector - * can be easily overridden by heavier selectors. For example, something as simple - * as changing the display style on a HTML list item would make hidden elements appear visible. - * This also becomes a bigger issue when dealing with CSS frameworks. - * - * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector - * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the - * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. - * - * ### Overriding .ng-hide - * - * If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by - * restating the styles for the .ng-hide class in CSS: - *
- * .ng-hide {
- *   //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
- *   display:block!important;
- *
- *   //this is just another form of hiding an element
- *   position:absolute;
- *   top:-9999px;
- *   left:-9999px;
- * }
- * 
- * - * Just remember to include the important flag so the CSS override will function. - * - * ## A note about animations with ngHide - * - * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression - * is true and false. This system works similar to the animation system present with ngClass, however, the - * only difference is that you must also include the !important flag to override the display property so - * that you can perform an animation when the element is hidden during the time of the animation. - * - *
- * //
- * //a working example can be found at the bottom of this page
- * //
- * .my-element.ng-hide-add, .my-element.ng-hide-remove {
- *   transition:0.5s linear all;
- *   display:block!important;
- * }
- *
- * .my-element.ng-hide-add { ... }
- * .my-element.ng-hide-add.ng-hide-add-active { ... }
- * .my-element.ng-hide-remove { ... }
- * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
- * 
- * - * @animations - * removeClass: .ng-hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden - * addClass: .ng-hide - happens after the ngHide expression evaluates to a non truthy value and just before the contents are set to visible - * - * @element ANY - * @param {expression} ngHide If the {@link guide/expression expression} is truthy then - * the element is shown or hidden respectively. - * - * @example - - - Click me:
-
- Show: -
- I show up when your checkbox is checked. -
-
-
- Hide: -
- I hide when your checkbox is checked. -
-
-
- - .animate-hide.ng-hide-add, - .animate-hide.ng-hide-remove { - -webkit-transition:all linear 0.5s; - -moz-transition:all linear 0.5s; - -o-transition:all linear 0.5s; - transition:all linear 0.5s; - display:block!important; - } - - .animate-hide.ng-hide-add.ng-hide-add-active, - .animate-hide.ng-hide-remove { - line-height:0; - opacity:0; - padding:0 10px; - } - - .animate-hide.ng-hide-add, - .animate-hide.ng-hide-remove.ng-hide-remove-active { - line-height:20px; - opacity:1; - padding:10px; - border:1px solid black; - background:white; - } - - .check-element { - padding:10px; - border:1px solid black; - background:white; - } - - - it('should check ng-show / ng-hide', function() { - expect(element('.doc-example-live .check-element:first:hidden').count()).toEqual(1); - expect(element('.doc-example-live .check-element:last:visible').count()).toEqual(1); - - input('checked').check(); - - expect(element('.doc-example-live .check-element:first:visible').count()).toEqual(1); - expect(element('.doc-example-live .check-element:last:hidden').count()).toEqual(1); - }); - -
- */ -var ngHideDirective = ['$animate', function($animate) { - return function(scope, element, attr) { - scope.$watch(attr.ngHide, function ngHideWatchAction(value){ - $animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide'); - }); - }; -}]; - -/** - * @ngdoc directive - * @name ng.directive:ngStyle - * - * @description - * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. - * - * @element ANY - * @param {expression} ngStyle {@link guide/expression Expression} which evals to an - * object whose keys are CSS style names and values are corresponding values for those CSS - * keys. - * - * @example - - - - -
- Sample Text -
myStyle={{myStyle}}
-
- - span { - color: black; - } - - - it('should check ng-style', function() { - expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); - element('.doc-example-live :button[value=set]').click(); - expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)'); - element('.doc-example-live :button[value=clear]').click(); - expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); - }); - -
- */ -var ngStyleDirective = ngDirective(function(scope, element, attr) { - scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) { - if (oldStyles && (newStyles !== oldStyles)) { - forEach(oldStyles, function(val, style) { element.css(style, '');}); - } - if (newStyles) element.css(newStyles); - }, true); -}); - -/** - * @ngdoc directive - * @name ng.directive:ngSwitch - * @restrict EA - * - * @description - * The ngSwitch directive is used to conditionally swap DOM structure on your template based on a scope expression. - * Elements within ngSwitch but without ngSwitchWhen or ngSwitchDefault directives will be preserved at the location - * as specified in the template. - * - * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it - * from the template cache), ngSwitch simply choses one of the nested elements and makes it visible based on which element - * matches the value obtained from the evaluated expression. In other words, you define a container element - * (where you place the directive), place an expression on the **on="..." attribute** - * (or the **ng-switch="..." attribute**), define any inner elements inside of the directive and place - * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on - * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default - * attribute is displayed. - * - * @animations - * enter - happens after the ngSwtich contents change and the matched child element is placed inside the container - * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM - * - * @usage - * - * ... - * ... - * ... - * - * - * @scope - * @param {*} ngSwitch|on expression to match against ng-switch-when. - * @paramDescription - * On child elements add: - * - * * `ngSwitchWhen`: the case statement to match against. If match then this - * case will be displayed. If the same match appears multiple times, all the - * elements will be displayed. - * * `ngSwitchDefault`: the default case when no other case match. If there - * are multiple default cases, all of them will be displayed when no other - * case match. - * - * - * @example - - -
- - selection={{selection}} -
-
-
Settings Div
-
Home Span
-
default
-
-
-
- - function Ctrl($scope) { - $scope.items = ['settings', 'home', 'other']; - $scope.selection = $scope.items[0]; - } - - - .animate-switch-container { - position:relative; - background:white; - border:1px solid black; - height:40px; - overflow:hidden; - } - - .animate-switch-container > div { - padding:10px; - } - - .animate-switch-container > .ng-enter, - .animate-switch-container > .ng-leave { - -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - - position:absolute; - top:0; - left:0; - right:0; - bottom:0; - } - - .animate-switch-container > .ng-enter { - top:-50px; - } - .animate-switch-container > .ng-enter.ng-enter-active { - top:0; - } - - .animate-switch-container > .ng-leave { - top:0; - } - .animate-switch-container > .ng-leave.ng-leave-active { - top:50px; - } - - - it('should start in settings', function() { - expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/); - }); - it('should change to home', function() { - select('selection').option('home'); - expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/); - }); - it('should select default', function() { - select('selection').option('other'); - expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/); - }); - -
- */ -var ngSwitchDirective = ['$animate', function($animate) { - return { - restrict: 'EA', - require: 'ngSwitch', - - // asks for $scope to fool the BC controller module - controller: ['$scope', function ngSwitchController() { - this.cases = {}; - }], - link: function(scope, element, attr, ngSwitchController) { - var watchExpr = attr.ngSwitch || attr.on, - selectedTranscludes, - selectedElements, - selectedScopes = []; - - scope.$watch(watchExpr, function ngSwitchWatchAction(value) { - for (var i= 0, ii=selectedScopes.length; i - - -
-
-
- {{text}} -
-
- - it('should have transcluded', function() { - input('title').enter('TITLE'); - input('text').enter('TEXT'); - expect(binding('title')).toEqual('TITLE'); - expect(binding('text')).toEqual('TEXT'); - }); - - - * - */ -var ngTranscludeDirective = ngDirective({ - controller: ['$transclude', '$element', '$scope', function($transclude, $element, $scope) { - // use evalAsync so that we don't process transclusion before directives on the parent element even when the - // transclusion replaces the current element. (we can't use priority here because that applies only to compile fns - // and not controllers - $scope.$evalAsync(function() { - $transclude(function(clone) { - $element.append(clone); - }); - }); - }] -}); - -/** - * @ngdoc directive - * @name ng.directive:script - * - * @description - * Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the - * template can be used by `ngInclude`, `ngView` or directive templates. - * - * @restrict E - * @param {'text/ng-template'} type must be set to `'text/ng-template'` - * - * @example - - - - - Load inlined template -
-
- - it('should load template defined inside script tag', function() { - element('#tpl-link').click(); - expect(element('#tpl-content').text()).toMatch(/Content of the template/); - }); - -
- */ -var scriptDirective = ['$templateCache', function($templateCache) { - return { - restrict: 'E', - terminal: true, - compile: function(element, attr) { - if (attr.type == 'text/ng-template') { - var templateUrl = attr.id, - // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent - text = element[0].text; - - $templateCache.put(templateUrl, text); - } - } - }; -}]; - -/** - * @ngdoc directive - * @name ng.directive:select - * @restrict E - * - * @description - * HTML `SELECT` element with angular data-binding. - * - * # `ngOptions` - * - * Optionally `ngOptions` attribute can be used to dynamically generate a list of `` - * DOM element. - * * `trackexpr`: Used when working with an array of objects. The result of this expression will be - * used to identify the objects in the array. The `trackexpr` will most likely refer to the - * `value` variable (e.g. `value.propertyName`). - * - * @example - - - -
-
    -
  • - Name: - [X] -
  • -
  • - [add] -
  • -
-
- Color (null not allowed): -
- - Color (null allowed): - - -
- - Color grouped by shade: -
- - - Select bogus.
-
- Currently selected: {{ {selected_color:color} }} -
-
-
-
- - it('should check ng-options', function() { - expect(binding('{selected_color:color}')).toMatch('red'); - select('color').option('0'); - expect(binding('{selected_color:color}')).toMatch('black'); - using('.nullable').select('color').option(''); - expect(binding('{selected_color:color}')).toMatch('null'); - }); - -
- */ - -var ngOptionsDirective = valueFn({ terminal: true }); -var selectDirective = ['$compile', '$parse', function($compile, $parse) { - //0000111110000000000022220000000000000000000000333300000000000000444444444444444440000000005555555555555555500000006666666666666666600000000000000007777000000000000000000088888 - var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/, - nullModelCtrl = {$setViewValue: noop}; - - return { - restrict: 'E', - require: ['select', '?ngModel'], - controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { - var self = this, - optionsMap = {}, - ngModelCtrl = nullModelCtrl, - nullOption, - unknownOption; - - - self.databound = $attrs.ngModel; - - - self.init = function(ngModelCtrl_, nullOption_, unknownOption_) { - ngModelCtrl = ngModelCtrl_; - nullOption = nullOption_; - unknownOption = unknownOption_; - } - - - self.addOption = function(value) { - optionsMap[value] = true; - - if (ngModelCtrl.$viewValue == value) { - $element.val(value); - if (unknownOption.parent()) unknownOption.remove(); - } - }; - - - self.removeOption = function(value) { - if (this.hasOption(value)) { - delete optionsMap[value]; - if (ngModelCtrl.$viewValue == value) { - this.renderUnknownOption(value); - } - } - }; - - - self.renderUnknownOption = function(val) { - var unknownVal = '? ' + hashKey(val) + ' ?'; - unknownOption.val(unknownVal); - $element.prepend(unknownOption); - $element.val(unknownVal); - unknownOption.prop('selected', true); // needed for IE - } - - - self.hasOption = function(value) { - return optionsMap.hasOwnProperty(value); - } - - $scope.$on('$destroy', function() { - // disable unknown option so that we don't do work when the whole select is being destroyed - self.renderUnknownOption = noop; - }); - }], - - link: function(scope, element, attr, ctrls) { - // if ngModel is not defined, we don't need to do anything - if (!ctrls[1]) return; - - var selectCtrl = ctrls[0], - ngModelCtrl = ctrls[1], - multiple = attr.multiple, - optionsExp = attr.ngOptions, - nullOption = false, // if false, user will not be able to select it (used by ngOptions) - emptyOption, - // we can't just jqLite('