13 |
14 |
15 | config
16 |
17 | rootUrl = {url}; //""
18 | log = {function}; //angular.noop;
19 | imagePath = {path to spinner}; //"spinner.gif";
20 | error = {function}; //angular.noop;
21 | success = {function}; //angular.noop;
22 | enableSpinner = {true|false}; //true
23 |
24 | arguments available
25 | $data
26 | $header
27 | $config
28 | $status
29 |
30 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "angular-cog",
3 | "version": "1.0.0",
4 | "description": "declarative $http for angularjs",
5 | "main": "Gruntfile.js",
6 | "preinstall" : "npm install -g grunt && npm install grunt-cli -g",
7 | "devDependencies": {
8 | "grunt": "~0.4.1",
9 | "grunt-contrib-concat": "*",
10 | "grunt-contrib-uglify": "*",
11 | "grunt-contrib-copy": "*",
12 | "grunt-contrib-clean": "*",
13 | "grunt-ngmin": "0.0.3",
14 | "grunt-contrib-watch": "~0.5.3",
15 | "karma": "^0.12.6",
16 | "grunt-karma": "^0.8.2",
17 | "karma-jasmine": "^0.1.5",
18 | "karma-chrome-launcher": "^0.1.3",
19 | "karma-coverage": "^0.2.1"
20 | },
21 | "scripts": {
22 | "test": "./node_modules/karma/bin/karma start"
23 | },
24 | "repository": "",
25 | "author": "chinmaymk",
26 | "license": "MIT"
27 | }
28 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2014 Chinmay Kulkarni
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/example/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | angular-cog demo!
6 |
7 |
8 |
9 |
10 |
11 | {{users}}
12 |
13 |
14 |
15 |
16 |
17 |
18 |
28 |
29 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/Gruntfile.js:
--------------------------------------------------------------------------------
1 | module.exports = function(grunt) {
2 |
3 | grunt.initConfig({
4 | ngmin: {
5 | directives: {
6 | src: ['src/*.js'],
7 | dest: 'build/directives.js'
8 | }
9 | },
10 | pkg: grunt.file.readJSON('package.json'),
11 | concat: {
12 | dist: {
13 | src: ['build/*.js'],
14 | dest: 'dist/angular-cog.js'
15 | }
16 | },
17 | uglify: {
18 | options: {
19 | banner: '/*! <%= pkg.name %> - v<%= pkg.version %> */'
20 | },
21 | dist: {
22 | src: 'dist/angular-cog.js',
23 | dest: 'dist/angular-cog.min.js'
24 | }
25 | },
26 | clean: ["build"],
27 | watch: {
28 | scripts: {
29 | files: ['src/**/*.js', 'tests/**/*.js'],
30 | tasks: ['ngmin', 'uglify', 'clean', 'karma:unit:run'],
31 | options: {
32 | debounceDelay: 250,
33 | },
34 | }
35 | },
36 | karma: {
37 | unit: {
38 | configFile: 'karma.conf.js',
39 | // run karma in the background
40 | background: true,
41 | // which browsers to run the tests on
42 | browsers: ['Chrome']
43 | }
44 | }
45 | });
46 |
47 | grunt.loadNpmTasks('grunt-contrib-concat');
48 | grunt.loadNpmTasks('grunt-ngmin');
49 | grunt.loadNpmTasks('grunt-contrib-uglify');
50 | grunt.loadNpmTasks('grunt-contrib-copy');
51 | grunt.loadNpmTasks('grunt-contrib-clean');
52 | grunt.loadNpmTasks('grunt-contrib-watch');
53 | grunt.loadNpmTasks('grunt-karma');
54 |
55 | grunt.registerTask('default', ['ngmin', 'concat', 'uglify', 'clean']);
56 |
57 | };
58 |
--------------------------------------------------------------------------------
/karma.conf.js:
--------------------------------------------------------------------------------
1 | var grunt = require('grunt');
2 | module.exports = function(karma) {
3 | karma.set({
4 | /**
5 | * From where to look for files, starting with the location of this file.
6 | */
7 | basePath: '.',
8 |
9 | /**
10 | * This is the list of file patterns to load into the browser during testing.
11 | */
12 | files: [
13 | "bower_components/angular/angular.min.js",
14 | "bower_components/angular/angular-mocks.js",
15 | "dist/*.js",
16 | "tests/*.js"
17 | ],
18 |
19 | preprocessors: {
20 | 'dist/*.js': ['coverage']
21 | },
22 |
23 | frameworks: ['jasmine'],
24 | plugins: ['karma-jasmine', 'karma-chrome-launcher', 'karma-coverage'],
25 |
26 | logLevel: 'WARN',
27 | /**
28 | * How to report, by default.
29 | */
30 | reporters: ['dots', 'coverage'],
31 |
32 | coverageReporter: {
33 | type: 'html',
34 | dir: 'coverage/'
35 | },
36 | /**
37 | * On which port should the browser connect, on which port is the test runner
38 | * operating, and what is the URL path for the browser to use.
39 | */
40 | port: 7019,
41 | urlRoot: '/',
42 |
43 | /**
44 | * Disable file watching by default.
45 | */
46 | autoWatch: true,
47 |
48 | /**
49 | * The list of browsers to launch to test ondest * default, but other browser names include:
50 | * Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS
51 | *
52 | * Note that you can also use the executable name of the browser, like "chromium"
53 | * or "firefox", but that these vary based on your operating system.
54 | *
55 | * You may also leave this blank and manually navigate your browser to
56 | * http://localhost:9018/ when you're running tests. The window/tab can be left
57 | * open and the tests will automatically occur there during the build. This has
58 | * the aesthetic advantage of not launching a browser every time you save.
59 | */
60 | browsers: [
61 | 'Chrome'
62 | ]
63 | });
64 | };
--------------------------------------------------------------------------------
/tests/angular-cog.tests.js:
--------------------------------------------------------------------------------
1 | describe('angular-cog directive', function() {
2 |
3 | // we declare some global vars to be used in the tests
4 | var elm, // our directive jqLite element
5 | scope, // the scope where our directive is inserted
6 | httpBackend;
7 |
8 | // load the modules we want to test
9 | beforeEach(module('angularCog'));
10 |
11 | // before each test, creates a new fresh scope
12 | // the inject function interest is to make use of the angularJS
13 | // dependency injection to get some other services in our test
14 | // here we need $rootScope to create a new scope
15 | beforeEach(inject(function($rootScope, $compile, $httpBackend) {
16 | scope = $rootScope.$new();
17 | scope.success = function() {
18 | scope.done = true;
19 | }
20 | scope.error = function() {
21 | scope.notdone = true;
22 | }
23 | httpBackend = $httpBackend;
24 | httpBackend.when("GET", "/users").respond([{}, {}, {}]);
25 | httpBackend.when("GET", "/notusers").respond(404);
26 | }));
27 |
28 | afterEach(function() {
29 | httpBackend.verifyNoOutstandingExpectation();
30 | httpBackend.verifyNoOutstandingRequest();
31 | });
32 |
33 | function compileDirective(tpl) {
34 | // function to compile a fresh directive with the given template, or a default one
35 | // compile the tpl with the $rootScope created above
36 | // wrap our directive inside a form to be able to test
37 | // that our form integration works well (via ngModelController)
38 | // our directive instance is then put in the global 'elm' variable for further tests
39 | var template = tpl || '';
40 |
41 | // inject allows you to use AngularJS dependency injection
42 | // to retrieve and use other services
43 | inject(function($compile) {
44 | $compile(template)(scope);
45 | });
46 | // $digest is necessary to finalize the directive generation
47 | scope.$digest();
48 | }
49 |
50 | // make successful request
51 | it('should make a get request to /users', function() {
52 | compileDirective('');
53 | httpBackend.flush();
54 | expect(scope.done).toBe(true);
55 | });
56 |
57 | // make successful request
58 | it('should make a failed get request to /users', function() {
59 | compileDirective('');
60 | httpBackend.flush();
61 | expect(scope.notdone).toBe(true);
62 | });
63 | });
--------------------------------------------------------------------------------
/dist/angular-cog.min.js:
--------------------------------------------------------------------------------
1 | /*! angular-cog - v1.0.0 */angular.module("angularCog",[]),angular.module("angularCog").directive("cogGet",["MakeRequestService",function(a){return{restrict:"A",scope:!0,link:function(b,c,d){d.cogTrigger?b.$watch(d.cogTrigger,function(c){c&&a("get",null,b,d)}):a("get",null,b,d)}}}]),angular.module("angularCog").directive("cogPost",["MakeRequestService",function(a){return{restrict:"A",require:"^form",scope:!0,link:function(b,c,d){c.bind("submit",function(){var c=b[d.cogModel];a("post",c,b,d)})}}}]),angular.module("angularCog").directive("cogPut",["MakeRequestService",function(a){return{restrict:"A",require:"^form",scope:!0,link:function(b,c,d){c.bind("submit",function(){var c=b[d.cogModel];a("put",c,b,d)})}}}]),angular.module("angularCog").directive("cogDelete",["MakeRequestService",function(a){return{restrict:"A",scope:!0,link:function(b,c,d){c.bind("click",function(){console.log("called"),a("delete",null,b,d)})}}}]),angular.module("angularCog").factory("MakeRequestService",["$http","CogConfig","SpinnerService",function(a,b,c){function d(d,f,g,h){function i(a,d,e,f){g.$data=a,g.$status=d,g.$headers=e,g.$config=f,b.enableSpinner&&!h.cogNoSpinner&&c.stop(),b.log(a,d,e,f)}a({method:d,url:e(d,h),data:f,config:g[h.CogConfig]}).success(function(a,c,d,e){i(a,c,d,e),g.$eval(h.cogSuccess),b.success(a,c,d,e)}).error(function(a,c,d,e){i(a,c,d,e),g.$eval(h.cogError),b.error(a,c,d,e)}),g.$$phase||g.$apply(),b.enableSpinner&&!h.cogNoSpinner&&c.spin()}function e(a,c){var d=c.cogAbsoluteUrl?"":b.rootUrl;switch(a){case"get":d+=c.cogGet;break;case"post":d+=c.cogPost;break;case"put":d+=c.cogPut;break;case"delete":d+=c.cogDelete}return d}return d}]),angular.module("angularCog").service("SpinnerService",["CogConfig",function(){var a=["position:absolute;","top:50%;","left:50%;","z-index:2000"].join(""),b=angular.element("
");b.attr("style",a);var c=["position:fixed;","top:0;","left:0;","width:100%;","height:100%;","background:white;","text-align:center;","opacity:0.7;"].join(""),d=angular.element("");d.attr("style",c);var e=[],f=!1;return{spin:function(){e.push(1),f||(angular.element(document.body).append(d),angular.element(document.body).append(b),f=!0)},stop:function(){e.pop(),0==e.length&&(d.remove(),b.remove(),f=!1)}}}]),angular.module("angularCog").provider("CogConfig",function(){this.rootUrl="",this.log=angular.noop,this.imagePath="spinner.gif",this.error=angular.noop,this.success=angular.noop,this.enableSpinner=!0;var a=this;this.$get=function(){return a}});
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | angular-cog
2 | ===========
3 | declarative ajax requests for angularjs
4 |
5 | ### Cog?
6 | A subordinate member of an organization who performs necessary but usually minor or routine functions.
7 |
8 | ### Groundwork first
9 | angular-cog exposes few directives that act as helpers for ajax requests. For every request 4 attributes are most important
10 |
11 | 1. Url
12 | 2. Data to be sent
13 | 3. Headers
14 | 3. Whether reponse is success or error
15 |
16 | angular-cog allows you to configure these from html directive and remove the clutter from javascript.
17 |
18 | ### Installation
19 | Installation is very straight forward. Grab the latest zip from github. Copy angular-cog.min.js in your root, and refer it in your page.
20 | ```html
21 |
22 | ```
23 | Then,add it as dependency in your module
24 | ```javascript
25 | angular.module('yourApp', ['angularCog']);
26 | ```
27 | ### Directive
28 | ```html
29 |
30 |
38 |
39 | ```
40 |
41 | Attribute | Meaning | Example
42 | --- | --- | ---
43 | ```cog-*verb*``` | url to call, [get,post,put,delete] decides the http verb | ```cog-get="/users"```, ```cog-post="/users"```
44 | ```cog-model``` | data that will be passed with post and put request | ```cog-model="user"```
45 | ```cog-success``` | expression to evaluate if response is 200 | ```cog-success="users = $data"```, ```cog-success="setUsers($data)```
46 | ```cog-error``` | expression to evaluate if response is not 200 | ```cog-error="error($headers)"```
47 | ```cog-trigger``` | by default, request will be sent as soon as directive is compiled, in case you would like to delay the request you could use cog-trigger. angular-cog will watch the expression and fire the request as soon as it becomes true. **applicable to cog-get only** | ```cog-trigger="user != null"```
48 | ```cog-no-spinner``` | if you don't want to display spinner for this particular request, refer [spinner](#spinner) for more information | ```cog-no-spinner="true"```
49 | ```cog-absolute-url``` | by default CogConfig.rootUrl will be prepended to every url, if you don't want to then use this attribute | ```cog-absolute-url="true"```
50 | ```cog-config``` | header object to pass to angular $http |
51 |
52 | **Note:** ```cog-post``` and ```cog-put``` are only allowed on ```
106 | ```
107 | **cog-put**
108 | ```html
109 |
111 |
112 |
118 | ```
119 | **Note:** for ```cog-put``` and ```cog-post```, ```cog-model``` is necessary. else the request will be sent with blank payload. Also, ```cog-put``` and ```cog-post``` can be only used with ```