Giter Club home page Giter Club logo

gulp-ng-html2js's Introduction

gulp-ng-html2js NPM version Build Status Dependency Status

A plugin for gulp which generates AngularJS modules, which pre-load your HTML code into the $templateCache. This way AngularJS doesn't need to request the actual HTML files anymore.

Usage

First, install gulp-ng-html2js as a development dependency:

npm install --save-dev gulp-ng-html2js

Then, add it to your gulpfile.js:

var ngHtml2Js = require("gulp-ng-html2js");

gulp.src("./partials/*.html")
	.pipe(ngHtml2Js({
		moduleName: "MyAwesomePartials",
		prefix: "/partials"
	}))
	.pipe(gulp.dest("./dist/partials"));

The main reason to use this module would be optimization. By pre-loading the HTML files, you can spare requests and loading time when the files are actually needed. When you are optimizing, you should do it properly. So, we should add the following plugins: gulp-minify-html, gulp-uglify, and gulp-concat:

var ngHtml2Js = require("gulp-ng-html2js");
var minifyHtml = require("gulp-minify-html");
var concat = require("gulp-concat");
var uglify = require("gulp-uglify");

gulp.src("./partials/*.html")
	.pipe(minifyHtml({
		empty: true,
		spare: true,
		quotes: true
	}))
	.pipe(ngHtml2Js({
		moduleName: "MyAwesomePartials",
		prefix: "/partials"
	}))
	.pipe(concat("partials.min.js"))
	.pipe(uglify())
	.pipe(gulp.dest("./dist/partials"));

This way you end up with 1 single, minified Javascript file, which pre-loads all the (minified) HTML templates.

If you have your modules sorted into directories that match the module name, you could do something like this:

// This picks up files like this:
//   partials/date-picker/year.html (as well as month.html, day.html)
//   partials/expanded-combo-box/combobox.html
//   partials/forms/feedback.html (as well as survey.html, contact.html)
// Returns modules like this:
//   datePicker, expandedComboBox, forms
gulp.src("./partials/**/*.html")
    .pipe(ngHtml2Js({
		moduleName: function (file) {
			var pathParts = file.path.split('/');
			var folder = pathParts[pathParts.length - 2];
			return folder.replace(/-[a-z]/g, function (match) {
				return match.substr(1).toUpperCase();
			});
		}
	}))
	.pipe(concat("partials.min.js"))
	.pipe(gulp.dest('./dist/partials'));
}

API

ngHtml2Js(options)

options.moduleName

Type: String or Function

The name of the generated AngularJS module. Uses the file url if omitted.

When this is a function, the returned value will be the module name. The function will be passed the vinyl file object so the module name can be determined from the path, content, last access time or any other property. Returning undefined will fall back to the file url.

options.declareModule

Type: Boolean

Whether to attempt to declare a new module (used with options.moduleName). True if omitted.

Set this to false if options.moduleName is already declared.

options.prefix

Type: String

The prefix which should be prepended to the file path to generate the file url.

options.stripPrefix

Type: String

The prefix which should be subtracted from the file path to generate the file url.

options.rename

Type: Function

A function that allows the generate file url to be manipulated. For example:

function (templateUrl, templateFile) {
  return templateUrl.replace('.tpl.html', '.html');
}

options.template

Type: String

A custom Lodash template for generating the Javacript code. The template is called with the following params:

  • moduleName: the resulting module name.
  • template
    • url: the resulting template url.
    • content: the HTML content of the input file.
    • escapedContent: the escaped HTML content of the input file. Note: the HTML content is escaped for usage in a single quoted string.
    • prettyEscapedContent: the readable, escaped HTML content of the input file.

Example

{
  template: "$templateCache.put('<%= template.url %>', '<%= template.escapedContent %>');"
}

options.extension

Type: String

The file extension of the generated files. Defaults to .js. Can be used to generate TypeScript files and create a gulp TypeScript - job to convert them. For a working example take a look at angular-systemjs-typescript-boilerplate

options.export

Type: String

  • commonjs: export the angular module using module.exports =
  • system: export the angular module using export default

Note this does not export anything with declareModule set to true.

Example

{
  export: 'commonjs'
}
{
  export: 'system'
}

License

MIT License

gulp-ng-html2js's People

Contributors

ajoslin avatar cameronmaske avatar dominicboettger avatar fidian avatar lookfirst avatar marklagendijk avatar nickescallon avatar smonkey72 avatar thedancingcode avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

gulp-ng-html2js's Issues

Angular templates with {{}} break the output

Just started using gulp and gulp-ng-html2js. My first attempt I believe I have a bug. Here's what I have:

main.tpl.html

<div>
   {{ message }}
</div>

partners.tpl.html

<h2>Partners Template</h2>

gulp

gulp.src('./partials/*.tpl.html')
  .pipe(ngHtml2Js({
     moduleName: 'MyAwesomePartials',
     prefix: '/partials/',
     rename: function(url) { return url.replace('.tpl.html', '.html'); }
  }))
  .pipe(rename('templates.js'))
  .pipe(gulp.dest('./dist/partials/'));

Output to templates.js:

(function(module) {
try {
  module = angular.module('MyAwesomePartials');
} catch (e) {
  module = angular.module('MyAwesomePartials', []);
}
module.run(['$templateCache', function($templateCache) {
  $templateCache.put('/partials/partners.html',
    '<h2>Partners Template</h2>');
}]);
})();
div>');
}]);
})();

What are the differences with gulp-angular-templatecache?

Can you please elaborate what the differences with gulp-angular-templatecache are? I am seeing gulp-ng-html2js used in more recent projects occasionally...but it's not clear whether this is incidental or not.
Any thoughts are appreciated!

Mo

The options.declareModule apparently changes the order between modules and templates

The options.declareModule (true by default) was leading me to an error (Failed to load template: ...). Because it injects my app module definition AFTER one of the templaceCache statements in the final .js, forcing them to create a new app module (since mine will only be defined later).

Something like that:

// gulpfile.js. declareModule: true by default
ngHtml2js({
    moduleName: "myApp"
})

// final app.min.js
// 0 my directive
angular.module('myDirectives', []).directive('myDirective', ...
    return {
        templateUrl: 'partials/myDirectivePartial.html'
        // ...

// 1 my controller
angular.module('myControllers', []).directive('myController', ...

// 2 my controller's PARTIAL template cache
(function(module) {
    try {
      module = angular.module('myApp');
    } catch (e) {
      module = angular.module('myApp', []);
    }
    module.run(['$templateCache', function($templateCache) {
      $templateCache.put('partials/myControllerPartial.html', '<div>...</div>');
    }]);
})();

// 3 my app (who binds partial to my controller)
angular.module('myApp', [...])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.
            when('/', {
                templateUrl: 'partials/myControllerPartial.html',
                controller: 'MyControllerCtrl'
            })
            // ...
}])

// 4 my directive's PARTIAL template cache
(function(module) {
    try {
      module = angular.module('myApp');
    } catch (e) {
      module = angular.module('myApp', []);
    }
    module.run(['$templateCache', function($templateCache) {
      $templateCache.put('partials/myDirectivePartial.html', '<div>...</div>');
    }]);
})();

As a result, myDirective can find partials/myDirectivePartial.html, but myApp can't find partials/myControllerPartial.html.

When I set this option to false, all templaceCache statements are injected in the end of the file -- and now, of course, they do not try to create a new module.

I do not know if I get wrong the idea of this option, but for me, it should false as default. Or, all templaceCache statements should be injected in the end of the file anyway (after a possible module definition before).

Thanks for this lib, very useful! :)

module.exports the angular.module()

Can I have an option to export the angular module that is created for the template?

module.exports = angular.module("forms.tpl.html", []).run(["$templateCache", function ($templateCache) {
  $templateCache.put("forms.tpl.html", "<h5>A form</h5><input type=\"text\">");
}]);

The benefit being that I can then do something like this:

define(['form.tpl'], function(formTpl) {
    angular.module('forms', [formTpl.name]);
})

I'm happy to submit a pull request, I just want to know it'll get integrated and not rejected. =)

Adding generated module to app

Hi

This is a great plugin but I have an issue with the generated module - after you have your gulp task create the module with the template, how do you get to load that module into your app dynamically? How does this work during development & deployment? Would you only load the module generated by gulp-ng-html2js when deploying (using gulp as your packaging processor) or would you expect to to perform the html2js as part of development also?

Thanks!
Josh

Maintained?

Is this project still maintained?

If not i will create a fork and publish a new version with typescript support.

Suggestion/question about output

Hey

Thanks for your work on this! From my point of view it seems like probably the best of the few Gulp html2js plugins available simply because it follows the Gulp way (not trying to do too much).

I have a suggestion for the output though. Unless I'm missing something it seems like only two sorts of output are possible. 1) Setup all the templates in one module and use quite a few bytes repeating the try/catch module setup code for each template, or 2) in the absence of a module name option then create one module per template. The two sorts of output are mutually exclusive.

I think generally I favour option 2) since its great to be able to pull in templates individually in isolated unit tests etc. However, its also handy to be able to pull in all your templates at once too - for example when setting up your module dependencies on your main app.

Perhaps output that attempted to get the best of both worlds would be ideal? i.e. one module per template, but also a a module that aggregated all templates?

I'm achieving this at the moment in my build by adding an extra task after the ngHtml2Js and concat tasks that aggregates all the templates into one module and prefixes the generated file with the new definition. It looks like this:

var through = require('through2');
var util = require('util');

module.exports = function (moduleName) {

    stream = through.obj(function (file,enc,cb) {
        var templates = file.contents.toString().match(/^angular\.module\('(.*?)'/gm);
        templates.forEach(function (template,index) {
            template = template.replace(/angular.module\(/g,'');
            templates[index] = template;
        });
        var mod = util.format('angular.module(\'%s\',[%s]);\n\n',moduleName,templates.join(','));
        file.contents = Buffer.concat([new Buffer(mod),file.contents]);
        this.push(file);
        cb();
    });

    return stream;
}

And I use it like this:

gulp.task('tpl',function () {
        return gulp.src('src/**/*tpl.html')
            .pipe(html2js())
            .pipe(concat('templates.js'))
            .pipe(aggtpl('templates-mod'))
            .pipe(gulp.dest('src'));
    });

And it generates output a bit like this:

angular.module('templates-mod',['home-tpl.html','project-tpl.html']);

angular.module('home-tpl.html', []).run(['$templateCache', function($templateCache) {
  $templateCache.put('home-tpl.html',
    '<h1>Home</h1>');
}]);

angular.module('project-tpl.html', []).run(['$templateCache', function($templateCache) {
  $templateCache.put('project-tpl.html',
    '<h1>Project</h1>');
}]);

What do you think? Do you think there's scope for bringing this sort of functionality into your task?

Local Npm module "grunt-ng-ng_html2js" not found.

0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/nodejs',
1 verbose cli '/usr/bin/npm',
1 verbose cli 'install',
1 verbose cli 'grunt-ng-ng_html2js',
1 verbose cli '--save-dev' ]
2 info using [email protected]
3 info using [email protected]
4 silly loadCurrentTree Starting
5 silly install loadCurrentTree
6 silly install readLocalPackageData
7 silly fetchPackageMetaData grunt-ng-ng_html2js
8 silly fetchNamedPackageData grunt-ng-ng_html2js
9 silly mapToRegistry name grunt-ng-ng_html2js
10 silly mapToRegistry using default registry
11 silly mapToRegistry registry https://registry.npmjs.org/
12 silly mapToRegistry data Result {
12 silly mapToRegistry raw: 'grunt-ng-ng_html2js',
12 silly mapToRegistry scope: null,
12 silly mapToRegistry name: 'grunt-ng-ng_html2js',
12 silly mapToRegistry rawSpec: '',
12 silly mapToRegistry spec: 'latest',
12 silly mapToRegistry type: 'tag' }
13 silly mapToRegistry uri https://registry.npmjs.org/grunt-ng-ng_html2js
14 verbose request uri https://registry.npmjs.org/grunt-ng-ng_html2js
15 verbose request no auth needed
16 info attempt registry request try #1 at 11:49:37 PM
17 verbose request id aee1949441601a24
18 http request GET https://registry.npmjs.org/grunt-ng-ng_html2js
19 http 404 https://registry.npmjs.org/grunt-ng-ng_html2js
20 verbose headers { 'content-type': 'application/json',
20 verbose headers 'cache-control': 'max-age=0',
20 verbose headers 'content-length': '2',
20 verbose headers 'accept-ranges': 'bytes',
20 verbose headers date: 'Thu, 14 Apr 2016 21:49:38 GMT',
20 verbose headers via: '1.1 varnish',
20 verbose headers age: '0',
20 verbose headers connection: 'keep-alive',
20 verbose headers 'x-served-by': 'cache-ams4124-AMS',
20 verbose headers 'x-cache': 'MISS',
20 verbose headers 'x-cache-hits': '0',
20 verbose headers 'x-timer': 'S1460670578.001257,VS0,VE96',
20 verbose headers vary: 'Accept-Encoding' }
21 silly get cb [ 404,
21 silly get { 'content-type': 'application/json',
21 silly get 'cache-control': 'max-age=0',
21 silly get 'content-length': '2',
21 silly get 'accept-ranges': 'bytes',
21 silly get date: 'Thu, 14 Apr 2016 21:49:38 GMT',
21 silly get via: '1.1 varnish',
21 silly get age: '0',
21 silly get connection: 'keep-alive',
21 silly get 'x-served-by': 'cache-ams4124-AMS',
21 silly get 'x-cache': 'MISS',
21 silly get 'x-cache-hits': '0',
21 silly get 'x-timer': 'S1460670578.001257,VS0,VE96',
21 silly get vary: 'Accept-Encoding' } ]
22 silly fetchPackageMetaData Error: Registry returned 404 for GET on https://registry.npmjs.org/grunt-ng-ng_html2js
22 silly fetchPackageMetaData at makeError (/usr/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:264:12)
22 silly fetchPackageMetaData at CachingRegistryClient. (/usr/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:242:14)
22 silly fetchPackageMetaData at Request._callback (/usr/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:172:14)
22 silly fetchPackageMetaData at Request.self.callback (/usr/lib/node_modules/npm/node_modules/request/request.js:200:22)
22 silly fetchPackageMetaData at emitTwo (events.js:100:13)
22 silly fetchPackageMetaData at Request.emit (events.js:185:7)
22 silly fetchPackageMetaData at Request. (/usr/lib/node_modules/npm/node_modules/request/request.js:1041:10)
22 silly fetchPackageMetaData at emitOne (events.js:95:20)
22 silly fetchPackageMetaData at Request.emit (events.js:182:7)
22 silly fetchPackageMetaData at IncomingMessage. (/usr/lib/node_modules/npm/node_modules/request/request.js:968:12)
22 silly fetchPackageMetaData error for grunt-ng-ng_html2js { [Error: Registry returned 404 for GET on https://registry.npmjs.org/grunt-ng-ng_html2js] pkgid: 'grunt-ng-ng_html2js', statusCode: 404, code: 'E404' }
23 silly rollbackFailedOptional Starting
24 silly rollbackFailedOptional Finishing
25 silly runTopLevelLifecycles Starting
26 silly runTopLevelLifecycles Finishing
27 silly install printInstalled
28 verbose stack Error: Registry returned 404 for GET on https://registry.npmjs.org/grunt-ng-ng_html2js
28 verbose stack at makeError (/usr/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:264:12)
28 verbose stack at CachingRegistryClient. (/usr/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:242:14)
28 verbose stack at Request._callback (/usr/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:172:14)
28 verbose stack at Request.self.callback (/usr/lib/node_modules/npm/node_modules/request/request.js:200:22)
28 verbose stack at emitTwo (events.js:100:13)
28 verbose stack at Request.emit (events.js:185:7)
28 verbose stack at Request. (/usr/lib/node_modules/npm/node_modules/request/request.js:1041:10)
28 verbose stack at emitOne (events.js:95:20)
28 verbose stack at Request.emit (events.js:182:7)
28 verbose stack at IncomingMessage. (/usr/lib/node_modules/npm/node_modules/request/request.js:968:12)
29 verbose statusCode 404
30 verbose pkgid grunt-ng-ng_html2js
31 verbose cwd /home/ahmed/www-dev/ImmoB
32 error Linux 4.2.0-35-generic
33 error argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "grunt-ng-ng_html2js" "--save-dev"
34 error node v5.10.1
35 error npm v3.8.7
36 error code E404
37 error 404 Registry returned 404 for GET on https://registry.npmjs.org/grunt-ng-ng_html2js
38 error 404
39 error 404 'grunt-ng-ng_html2js' is not in the npm registry.
40 error 404 You should bug the author to publish it (or use the name yourself!)
41 error 404 Note that you can also install from a
42 error 404 tarball, folder, http url, or git url.
43 verbose exit [ 1, true ]

May load "templateUrl" from $TemplatCache first ?

At fromURL,May you load "templateUrl" from $TemplatCache first?.eg:

this.fromUrl = function (url, params) {
if (isFunction(url)) url = url(params);
if (url == null) return null;
else {
var t = $templateCache.get(url);
if(t) return t;
return $http
.get(url, { cache: $templateCache, headers: { Accept: 'text/html' }})
.then(function(response) { return response.data; });
}
};

Unmet Peer Dependency for LoDash

@marklagendijk
Lodash v3 is no longer supported, and it looks like v4 does not introduce any breaking changes for this package.

Can we increase the range of the supported lodash dependency to include v4 as proposed here: #28 ?

This would avoid unmet peer dependency warnings on npm install when using a supported version of lodash.

Multiple Prefixes & Sources

Awesome plugin - thank you. I'm working to output a single file with all the files from one directory, and select files from another, and output them with the correct prefixes. I don't want all the files in each directory as in the example. The closest I've gotten is using filter, however all the files end up with same prefix, 'views/includes/'.

I'd appreciate any ideas to join sources with different prefixes. Thank you.

templatesources is a directory, 'views'
t2, t3, etc are paths to specific files in 'views/includes'

  var filter = gulpFilter([templatesources],{restore:true});

  gulp.src([templatesources,t2,t3,t4,t5,t6,t7])
  .pipe(filter)
  .pipe(minifyHtml(
    {
    empty: true,
    spare: true,
    quotes: true
  }))
  .pipe(ngHtml2Js({
    moduleName: 'xApp',
    prefix: 'views/'
  }))
  .pipe(filter.restore)
  .pipe(minifyHtml(
    {
    empty: true,
    spare: true,
    quotes: true
  }))
  .pipe(ngHtml2Js({
    moduleName: 'xApp',
    prefix: 'views/includes/'
  }))
  .pipe(concat('templates.js'))
  .pipe(cachebust.resources())
  .pipe(cachebust.references())
  // write the file
  .pipe(gulp.dest(destPath));

Incorrect documentation

I was taking a look at using this:

.pipe(ngHtml2Js({
    moduleName: function (file) {
        var path = file.split('/'),
            folder = path[path.length - 2];
        return folder.replace(/-[a-z]/g, function (match) {
            return match.substr(1).toUpperCase();
        });
    }
}))

however it errors saying: http://www.screencast.com/t/218gbvm7ul

I believe you meant to say file.path.split...is that correct?

Replace deprecated dependency gulp-util

gulp-util has been deprecated recently. Continuing to use this dependency may prevent the use of your library with the latest release of Gulp 4 so it is important to replace gulp-util.

The README.md lists alternatives for all the components so a simple replacement should be enough.

Your package is popular but still relying on gulp-util, it would be good to publish a fixed version to npm as soon as possible.

See:

how to add dynamic module name for the templates

for example, this is the structure of my app:

/components
--appModule.jj
--appRoutes.js
--/home
----home.html //for the ui-router
----home.tpl.html. //for the directive
----homeModule.js
----homeDirective.js
----homeFactory.js
--/frameworks
----frameworks.html //for the ui-router
----frameworks.tpl.html. //for the directive
----frameworksModule.js
----frameworksDirective.js
----frameworksFactory.js

your plugin works perfectly, but all of the templates ends up with the same module name specified in the gulp.file:

gulp.task('templating', function () {

   return gulp.src("./public/components/**/*.html")
      .pipe(ngHtml2Js({
         moduleName: "app",
         prefix: "/components/"
      }))
      .pipe(gulp.dest("./public/components"));

});

I'm using 'gulp-concat' to specify the order of the files cuz each module need to be first before its providers(factories, directives, etc...)

so, the result is the following:

/*** for home ***/
(function() {
   'use strict';

   angular.module('home', []);

}());

(function(module) {
try {
  module = angular.module('app');
} catch (e) {
  module = angular.module('app', []);
}
module.run(['$templateCache', function($templateCache) {
  $templateCache.put('/components/home/home.html',
    '<home-directive></home-directive>');
}]);
})();


(function(module) {
try {
  module = angular.module('app');
} catch (e) {
  module = angular.module('app', []);
}
module.run(['$templateCache', function($templateCache) {
  $templateCache.put('/components/home/home.tpl.html',
    '<h1>Honey, I\'m home...</h1>');
}]);
})();

/*** for frameworks ***/

(function() {
   'use strict';

   angular.module('frameworks', []);

}());

(function(module) {
try {
  module = angular.module('app');
} catch (e) {
  module = angular.module('app', []);
}
module.run(['$templateCache', function($templateCache) {
  $templateCache.put('/components/frameworks/frameworks.html',
    '<frameworks-directive></frameworks-directive>');
}]);
})();


(function(module) {
try {
  module = angular.module('app');
} catch (e) {
  module = angular.module('app', []);
}
module.run(['$templateCache', function($templateCache) {
  $templateCache.put('/components/frameworks/frameworks.tpl.html',
    '<div class="table-responsive">\n' +
    '   <table class="table table-condensed">\n' +
    '      <thead>\n' +
    '      <tr>\n' +
    '         <th>id</th>\n' +
    '         <th>Name</th>\n' +
    '         <th>Company</th>\n' +
    '         <th>&nbsp;</th>\n' +
    '      </tr>\n' +
    '      </thead>\n' +
    '      <tbody>\n' +
    '      <tr ng-repeat="framework in frameworksCtrl.frameworks">\n' +
    '         <td>{{framework.id}}</td>\n' +
    '         <td>{{framework.name}}</td>\n' +
    '         <td>{{framework.company}}</td>\n' +
    '         <td>\n' +
    '            <span class="glyphicon glyphicon-remove"\n' +
    '                  ng-click="frameworksCtrl.deleteFramework(framework)">\n' +
    '            </span>\n' +
    '         </td>\n' +
    '      </tr>\n' +
    '      </tbody>\n' +
    '   </table>\n' +
    '</div>\n' +
    '\n' +
    '<!--<pre>{{frameworksCtrl.big | json}}</pre>-->');
}]);
})();

(function() {
   'use strict';

   angular
      .module('frameworks')
      .directive('frameworksDirective', frameworksDirective);

   frameworksDirective.$inject = ['$templateCache'];

   function frameworksDirective($templateCache) {

      return {
         scope: {},
         controller: FrameworksController,
         controllerAs: 'frameworksCtrl',
         bindToController: true,
         template: $templateCache.get('components/frameworks/frameworks.tpl.html')
      };

   }

   FrameworksController.$inject = ['frameworksFactory', '$scope'];

   function FrameworksController(frameworksFactory, $scope) {

      var self = this;

      activate();

      function activate() {

         frameworksFactory.getFrameworks().then(function (response) {
            self.frameworks = response;
         });

         frameworksFactory.getBigJSON().then(function (response) {
            self.big = response;
         });

      }

      self.deleteFramework = deleteFramework;

      function deleteFramework(framework) {

         var index = self.frameworks.indexOf(framework);
         self.frameworks.splice(index, 1);

      }

   }

}());

(function() {
   'use strict';

   angular
      .module('frameworks')
      .factory('frameworksFactory', frameworksFactory);

   frameworksFactory.$inject = ['API_URL', '$http', '$q', '$cacheFactory'];

   function frameworksFactory(API_URL, $http, $q, $cacheFactory) {

      var jeroCache = $cacheFactory('jeroCache');

      return {
          getFrameworks: getFrameworks,
          getBigJSON: getBigJSON
      };

      function getFrameworks() {

         return $q(function (resolve, reject) {

            $http({
               url: API_URL + '/frameworks',
               method: 'GET',
               cache: jeroCache
            })
            .then(function (promise) {
               resolve(promise.data);
            }, function (reason) {
               reject(reason);
            });

         });

      }

      function getBigJSON() {

         return $q(function (resolve, reject) {

            $http({
               url: API_URL + '/assets/bigJSON',
               method: 'GET'
            })
            .then(function (promise) {
               resolve(promise.data);
            }, function (reason) {
               reject(reason);
            });

         });

      }

   }

}());

so the issue is that every template needs to have their corresponding module name to properly make it work in the 'run' phase' cuz if don't, if everything is on 'app', it'll run once, but when the other modules loads, their don't have their run phase so they make the http request to grab the file, so every template must have their corresponding module name:

try {
  module = angular.module('home');
} catch (e) {
  module = angular.module('home', []);
}

try {
  module = angular.module('frameworks');
} catch (e) {
  module = angular.module('frameworks', []);
}

so their 'run' phase will work properly and cache the template's module so there's no an http request...

this is just an small part, currently I'm working on a very hugeeeeeeee angular app where there is like more than 130 script files... and I will like to improve it's performance by caching properly all of the templates.

hope to be clear on this, thanks for your attention :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.