Angular + RequireJs: Resolve templateUrls of directives - javascript

I use angularjs and requirejs in my spa. For the organization of imports and so on I use require. In requirejs I can use e.g. baseUrl: Every import path is resolved with the baseUrl. Now I would like to resolve the templateUrls the same way. Therefore I can use e.g.:
templateUrl = requirejs.toUrl("modules/test/chuck.directive.html")
The problem that I would like to resolve every templateUrl of every directive this way.
So: Is there a possibility to jump into the template loading process of directives in angular and run the above code?
Thanks for any hint.

I would decorate $templateRequest service if you know for sure that you want to intercept all template loading requests and modify template URL. Something like this:
.config(function($provide) {
$provide.decorator('$templateRequest', function($delegate) {
return function(tpl, ignoreRequestError) {
tpl = requirejs.toUrl(tpl); // modify original tpl
return $delegate.call(this, tpl, ignoreRequestError);
};
});
})

Related

Angular - Load custom template using dynamic path with fallback

I want to replace the following code in my routes:
angular.module('app').config ($stateProvider, $urlRouterProvider) ->
.state 'statistics',
controller: 'AppCtrl'
templateUrl: '/app/statistics.html'
By something like this:
angular.module('app').config ($stateProvider, $urlRouterProvider) ->
.state 'statistics',
controller: 'AppCtrl'
templateUrl: Something.resolveTemplatePath('/app/statistics.html')
My goal is to add a prefix based on some configuration, but I need to know if the path with the prefix actually exists.
I need to call this in my routes, so I probably need to put this function is a Provider, right? And I don't really know how to check if the template exists or not. I believe Angular makes an AJAX call to load the template and I saw that I could check if the file is found or not, but I'm not sure what the best solution is.
Because if the file with prefix doesn't exist, then I must load the file without prefix (fallback).
What is the best way to do that? Thanks.
Where would this configuration for the prefix exist? Inside your Angular code or would it be part of a build tool like Gulp/Grunt?
Assuming that this 'prefix' would be an Angular constant by the name TEMPLATE_PREFIX, you could use a combination of $templateCache and the templateProvider given by ui-router to do
templateProvider: Something.resolveTemplatePath('/app/statistics.html')
And the definition of Something as a service as -
angular.module('app').service('Something', function($templateCache, TEMPLATE_PREFIX) {
this.resolveTemplatePath = function(templateURL) {
return $templateCache.get(TEMPLATE_PREFIX + templateURL) || $templateCache.get(templateURL);
}
});
There's a great grunt build task for populating $templateCache - https://www.npmjs.com/package/grunt-angular-templates

RequireJS loading a file that needs current file as dependency

I am currently building a base for AngularJS in combination with RequireJS and so far I got everything working. there's just a little thing that I do not understand at this point. I have a file which creates the angular module, when this module is created it requires a controller and assigns it to the module. The strange thing though, the controller needs the module as dependency while in the module's file the module has not been returned yet because the require statement is executed before the return statement. This somehow seems to work but it has a bad smell to it.
Module file:
// Home is defined here and can later be used in controllers (and Services)
define('home', ['require', 'angular'], function(require, angular) {
var homeModule = angular.module('AngularBase.home', ['AngularBase.core']);
homeModule.config(['$controllerProvider', '$provide', '$compileProvider', function($controllerProvider, $provide, $compileProvider) {
// We need this in order to support lazy loading
homeModule.controller = $controllerProvider.register;
homeModule.factory = $provide.factory;
// And more, not relevant at this moment
}]);
// It loads the controller that depends on this module here
require(['modules/home/controllers/homeController'], function() {
// Dependencies loaded
});
// Yet in my mind controllers that need this module can only use it when the following return statement is called.
return homeModule;
});
Controller File:
// As you can see this controller depends on home while home hasn't returned its module yet
// Yet it seems to work just fine
define(['home'], function(home) {
home.controller('homeController', ['$scope', 'homeService', function($scope, homeService) {
$scope.title = 'Home controller';
}]);
});
I assume that it is not a good approach to do it like this and therefore I need some suggestions on how to make this happen in a clean way. I thought about grabbing the AngularBase.home module via angular.module('AngularBase.home') in the controller file and defining my controller on this. This however no longer allows me to insert a mockModule for testing in this controller via RequireJS's map function.
map: {
'*' : {
'home' : 'mock-module'
}
}
Any suggestions on how to refactor this into a more clean solution?
I have found the solution to my problem. In the end it seems to be just fine to do it the way I am currently doing it. When a file is called and has a define statement in it it will wait until all dependencies are available until the function is executed. This means that the controller will actually wait for the module to finish initializing before calling its function to register itself.
The way I am doing it above is just fine.
Source: http://www.slideshare.net/iivanoo/handlebars-and-requirejs (slides 11 till 24)

Best practice for including scripts in Angular templates?

I have an Angular SPA with several tabs, which are served by templates. Each of these tabs requires different scripts (both local and CDN), so I'd only like to load scripts when needed, ie I will need to include them inside the templates (or associated controllers) themselves.
So far, I've tried this approach:
// Start template
<data-ng-include src="http://maps.googleapis.com/maps/api/js"></data-ng-include>
// Rest of stuff
// End template
This doesn't seem to be working. Yes, I have jQuery included in the header. What is the best way to go about this? Seems like it should be much simpler to include scripts inside templates.
You can use any of the lazy loader (on demand loader) library like requireJS, ocLazyLoad.
I have successfully implemented ocLazyLoad in one of our enterprise application, because it provide lots of usefull features if you are developing modular Single Page Application:
Easy to implement. You can lazy load any resource anywhere inside your application
Dependencies are automatically loaded
Debugger friendly (no eval code)
Can load any client side resouce like js/css/json/html
Compatible with AngularJS 1.2.x/1.3.x/1.4.x
You can also load any resource inside service, factory, directive also.See example
Resolve any resource before executing any state if you are using ui.router library for routing.See example
You can also lazy load resource in .config() of any module.See example
It also gives you the functionalty of logging module loading events.
All references are taken from official website of ocLazyLoad
If you want to include JS. I would tell you , please use :
cLazyLoad JS
Here is example:
var myapp = angular.module('myApp', ['oc.lazyLoad']);
myApp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
template: '<div ui-view class="ngslide"></div>',
resolve: {
deps: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load([js/jquery.main.min.js','js/ie10-viewport-bug-workaround.js']);
}]
}
})
});
I use a simple directive for this (here :
interface AddScriptDirectiveAttributes extends IAttributes {
type: string;
src: string;
}
export function addScript(): IDirective {
return {
restrict: 'E',
link: function (scope: IScope, element: JQuery, attrs: AddScriptDirectiveAttributes) {
let script = document.createElement('script');
if (attrs.type) {
script.type = attrs.type;
}
script.src = attrs.src;
document.body.appendChild(script);
}
};
}
Usage would be something like this:
<add-script src="script" type="application/javascript"></add-script>

Properly loading controller path in ui-router

I'm working on a complex Angular app and I'd like to know if there is a proper way to load a controller file path in an ui-router.
Currently, I load every controllers file in the main view like this : <script src="myCtrl.js"></script>.
I know that I can use ui-router like this :
$state provider
.state('state1'), {
url: '/state1',
views : {
'area1' : {
templateUrl: 'myView.html',
controller: 'myCtrlName' // change this to load the file ?
},
... // some other area + templateUrl here
}
}
But it's used to load the controller name, not its path. I tried to find a way by using load or file functions instead, but it didn't make it.
Do you have any idea ?
Edit : Maybe it can help you to know thatmy goal is to load my controller file out of the html view in order to simplify the html file and simply add/delete controllers in the app.
According to Radim Köhler and these questions angular-ui-router with requirejs, lazy loading of controller + AngularAMD + ui-router + dynamic controller name?, I'll try to use RequireJS.
Thanks a lot guys :)

Can you use Angular dependency injection instead of RequireJS?

I'm starting with angular, how could I break alll the code from one app into many files?, I watched the 60ish minutes intro, and they mentioned that I could do this without requirejs or any other framework.
Lets say I have something like this that works just fine:
var app = angular.module('app', []);
app.factory('ExampleFactory', function () {
var factory = {};
factory.something = function(){
/*some code*/
}
return factory;
});
app.controller ('ExampleCtrl', function($scope, ExampleFactory){
$scope.something = function(){
ExampleFactory.something();
};
});
app.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'ExampleCtrl',
templateUrl: 'views/ExampleView.html'
})
.otherwise({ redirectTo: '/' });
});
What if I wanted to have it in separate files? like this
File One:
angular.module('factoryOne', [])
.factory('ExampleFactory', function () {
var factory = {};
factory.something = function(){
/*some code*/
}
return factory;
});
File Two:
angular.module('controllerOne', ['factoryOne'])
.controller ('ExampleCtrl', function($scope,ExampleFactory){
$scope.something = function(){
ExampleFactory.something();
};
});
File Three:
angular.module('routes', ['controllerOne'])
.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'ExampleCtrl',
templateUrl: 'views/ExampleView.html'
})
.otherwise({ redirectTo: '/' });
});
File four:
var app = angular.module('app', ['routes']);
I've tried it like this and it doesn't work.
Can I do something like this and just have a script tag for File Four in the main view? or do I have to have one script tag per file?.
Thanks for the help guys.
AngularJS does not currently have a script loader as part of the framework. In order to load dependencies, you will need to use a third party loader such as RequireJS, script.js, etc.
Per the Docs(http://docs.angularjs.org/guide/module#asynchronousloading):
Asynchronous Loading
Modules are a way of managing $injector
configuration, and have nothing to do with loading of scripts into a
VM. There are existing projects which deal with script loading, which
may be used with Angular. Because modules do nothing at load time they
can be loaded into the VM in any order and thus script loaders can
take advantage of this property and parallelize the loading process.
...or, as #xanadont explained, you can add <script> tags to your page for every file.
You must have a
<script src="file.js"></script>
per each file that you're using. It should work once you have all the references in place.
Or ... check out this article for a way to roll-your-own runtime resolution of controllers.
You've got to separate the idea of downloading from the idea of loading and executing in-memory. Use Yeoman/grunt or similar build tools to manage the process of adding individual files to the project for Angular's various modules controllers, directives, services, etc. that are attached to those modules. Then, at build-time, the files will be minified and concatenated for a speed/bandwidth improvement that's vastly superior to lazy-downloading of individual files.
Once you've dealt with the files, Angular handles the rest, executing dependencies only when they're actually needed.
In the example above, #Jose, your problem was that you're not attaching your dependencies properly to the original module. You're creating new modules and burying the dependencies inside of them. In the first version, you used var app to cache the reference to the module called 'app' and then did app.controller(), etc. So, you're calling the .controller() method on the app module.
But in the second, you still need to attach those dependencies to the main app module. To do that, you need to call angular.module('app') to access the original module, then you can chain a call to .controller() or .directive() from that module, once you've retrieved it.
Bottom-line, use Angular's constructs for the loading of Angular dependencies. If, after you've gotten all of that out of the way, you still want to use Require for loading third-party scripts, go ahead. But I recommend testing first to see if you're actually adding value.

Categories