Where should I use $templateCache? - angularjs

I want to use $templateCache service to add some html into the cache. In Angular documentation example, it only shows the case of using it in run:
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
$templateCache.put('templateId.html', 'This is the content of the template');
});
However, when I am trying to add some templates through myApp config, there seems to be injector error. Is there a way to use templateCache not in RUN?
Thanks

run is the correct place to use the $templateCache. Since $templateCache is a service, it's not accessible in the configuration phase, because it hasn't been created yet. config is used to configure services (like $templateCache) using their providers. You can only inject providers to config.

My opinion is that, most of the time, you shouldn't be writing code that accesses $templateCache directly at all. What you should be doing is using a build system such as gulp and a plugin such as gulp-angular-templatecache.
Then your templates are simply a bunch of .html files, your editor recognises them as html and does the appropriate linting while you edit, and all you have to do is ensure your app declares a dependency on the template module.
So the code you gave above would become:
var myApp = angular.module('myApp', ['myappTemplates']);
and the use of $templateCache inside .run() is pushed down to automatically generated code that you never see.

Related

Error in Dependency Injection when I try minify angular app

I have done a web application based in ASP MVC and angularJS, and everything works fine. Now, I want deploy it. In my bundleConfig I have put BundleTable.EnableOptimizations = true; to minified my scripts.
When I launch the app get a error:
Module 'dataService' is not available! You either misspelled...
In docs I have seen an interesting thing (it fits to error):
Careful: If you plan to minify your code, your service names will get renamed and break your app.
As docs suggests I use Inline Array Annotation. My code is:
app = angular.module("MyApp", ['ui.router', 'ui.bootstrap', 'kendo.directives', 'dataService', 'LoginFactory', 'globalService']);
in module dataService is:
app.service('dataService', ['$http', function($http) {
// service logic
}]);
I thought that would fix the error, but not.
PS: I have seen 3 differents methods of injection dependencies and I have used all. In example I use that because in docs is marked like preferred
replace app.Service with app.service.

angular module multiple dependancy using modernizr

I am using 'Modernizr' for detecting mobile devices.I have created 'touchevent.js' file for the mobile devices
In touchevent.js
`var touchApp = angular.module('ngTouchEvent', [])
In script.js
'var app = angular.module('myApp', [ 'ngTouchEvent' ]);
now I want to load touchevent.js only in mobile devices using modernizr.
I am using
Modernizr.load('touchevent.js');
I am facing problem like
[$injector:modulerr] Failed to instantiate module myApp
in other than mobile device.
I dont want to load touchevent.js in desktop.Can I have solution for multiple dependacy
Actually Modernizr is an javascript object which you can use directly in any angular controller or directive without specifying any dependency on angular app. You can create an provider like this to use Modernizr in controller or directive like this:
angular.module('myApp').provider('Modernizr', function() {
this.$get = function() {
return Modernizr || {};
};
});
Modernizr.mq()
You can have a look at this project which offer a base project for using AngularJS with RequireJS to load on demand the required js files.
https://github.com/tnajdek/angular-requirejs-seed
If your application is huge, it might be useful, otherwise it can be overkill because just the fact of using AngularJS reduce the amount of code to be written.
Hoping it will be helpful

How to dynamically include all template partials when using a module in AngularJS

I have several modules that require some template partials to be loaded whenever the module is used. I am storing these files in a folder called partials inside each module subfolder. My starting point for my app is meanjs, and I am storing partials file are in public/modules//partials/*.html.
I have seen several ng-include and directive examples, but being new to AngularJS each sample I read confuses me further as to what is best practice / most AngularJS appropriate way to do this.
Store your partials whenever you wants.
To load them all use angular template cache.
Use Grunt or gulp to generate automatically. Personally I use gulp.
Here is my working example of one of my project.
install nodejs and npm
npm intall gulp -g
npm install gulp-angular-templatecache
create gulpfile.js
var templateCache = require('gulp-angular-templatecache'),
watch = require('gulp-watch');
gulp.task('generate', function () {
gulp.src('public/*/partials/*.html')
.pipe(templateCache('templates.js', {module: 'YOURMODULENAME', standalone: false}))
.pipe(gulp.dest('public/js'));
});
gulp.task('watch-partials', function () {
gulp.watch('public/*/partials/*.html', ['generate']);
});
then use it like this:
gulp generate - to regenerate partials
gulp watch-partials - watch file changes, if partials are changed it automatically run generate task for you. :)
One more thing, dont forget to include template.js in your html file
<script src="public/js/template.js"></script>
Every time you change your partial dont forget to regenerate your template cache.
You should take advantage of $templateCache. In your partials folder define the templates like this:
angular.module('yourTemplateModule', []).run('$templateCache', function ($templateCache) {
$templateCache.put('yourTemplate', '<div>...some HTML here...</div>');
}
Then create a module, named for example 'app.tpls', which has as dependencies all your template modules. Inject it as dependency to your main app module, probably located in meanjs and now you have your templates ready whenever you need them in your application. You retrieve them by calling:
$templateCache.get('yourTemplate');

How to create an AngularJS service that is accessible from the default app / custom module

I am new to AngularJS (reading docs for a week or so) so bear with me :) I am trying to expose some 3rd party library (JayData) functionality to AngularJS controllers via the DI/service infrastructure.
Creating a service is a straightforward thing, as long as you can manage to create your own module for this, and set ng-app to that module.
var mod = angular.module('myModule', [], function ($provide) {
$provide.factory('$data', ['$scope', function (sc) {
return $data;
}]);
});
<html ng-app='myModule'></html>
In my case developers will create their own app/startup module, or will use the "default ng app" without specifying an kind of module names like <html ng-app="".
How can I register a service that is globally accessible like the built-in services like $scope or $http?
You can add components to the ng module, which is the default module, with angular.module("ng").service(...). As mentioned in the comments, this is a bad idea for several reasons, most prominently that the Angular team might provide a service with the same name later.
For reference, the preferred way is to define your own module such as myAwesomeDataModule and add it as a dependency in other modules: angular.module("myModule", ["myAwesomeDataModule"]).

Importance of order in registering provider and configuring a module in angular.js

it seems that from angular's point of view the order of registering of a service provider and the module configuration code is important: in order for the configuration code to find the provider, the provider should be registered before.
This was a total surprise for me, as I thought that angular first processes all provider registrations, to make them available for DI, and then calls config callbacks, like this:
module.config(function(myServiceProvider) {...});
Please see here a very short test that demonstrates the problem. It fails on "unknown provider", you can see it in the JS console: http://plnkr.co/edit/jGJmE2Fq7wOrwubdlTTX
Am I missing anything here? Is it an expected angular behavior?
Thanks.
Looks like this behavior has changed in more recent versions of Angular (not sure when exactly). I modified your Plunker to point from 1.0.7 to 1.3.0 and it worked without error as you had originally expected.
Similar example of code that works:
var myModule = angular.module('myModule', []);
myModule.config((myServiceProvider) => {
});
myModule.service('myService', () => {
});
Running a config for a provider before the provider is registered with the module should work just fine as you were expecting.
Reference
For reference, this reported issue appears to be the one to have fixed it: https://github.com/angular/angular.js/issues/6723
The Angular documentation for module state that:
Recommended Setup
While the example above is simple, it will not scale to large applications. Instead we recommend that you break your
application to multiple modules like this:
A service module, for service declaration
A directive module, for directive declaration
A filter module, for filter declaration
And an application level module which depends on the above modules, and which has initialization code.
As you are using a single module that you call app, you are creating a dependency between that module's config and declaration of a provider. What you should have done is to place all your providers into a separate module, such as:
var appr = angular.module('appr', [])
.provider('myService', function() {
this.$get = function() {};
})
Then you declare the dependency of your app using:
var app = angular.module('plunker', ['appr']);
Check out the updated Plunker: http://plnkr.co/edit/Ym3Nlsm1nX4wPaiuVQ3Y?p=preview
Also, instead of using the generic provider, consider using more specific implementation of provider such as controller, factory or service. Take a look at Module API documentation for more detail.

Resources