After the Angular app is loaded I need some of the templates to be available offline.
Something like this would be ideal:
$routeProvider
.when('/p1', {
controller: controller1,
templateUrl: 'Template1.html',
preload: true
})
This is an addition to the answer by #gargc.
If you don't want to use the script tag to specify your template, and want to load templates from files, you can do something like this:
myApp.run(function ($templateCache, $http) {
$http.get('Template1.html', { cache: $templateCache });
});
myApp.config(function ($locationProvider, $routeProvider) {
$routeProvider.when('/p1', { templateUrl: 'Template1.html' })
});
There is a template cache service: $templateCache which can be used to preload templates in a javascript module.
For example, taken from the docs:
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
$templateCache.put('templateId.html', 'This is the content of the template');
});
There is even a grunt task to pre-generate a javascript module from html files: grunt-angular-templates
Another way, perhaps less flexible, is using inline templates, for example, having a script tag like this in your index.html:
<script type="text/ng-template" id="templates/Template1.html">template content</script>
means that the template can be addressed later in the same way as a real url in your route configuration (templateUrl: 'templates/Template1.html')
I think I have a slightly improved solution to this problem based on Raman Savitski's approach, but it loads the templates selectively. It actually allows for the original syntax that was asked for like this:
$routeProvider.when('/p1', { controller: controller1, templateUrl: 'Template1.html', preload: true })
This allows you to just decorate your route and not have to worry about updating another preloading configuration somewhere else.
Here is the code that runs on start:
angular.module('MyApp', []).run([
'$route', '$templateCache', '$http', (function ($route, $templateCache, $http) {
var url;
for (var i in $route.routes) {
if ($route.routes[i].preload) {
if (url = $route.routes[i].templateUrl) {
$http.get(url, { cache: $templateCache });
}
}
}
})
]);
Preloads all templates defined in module routes.
angular.module('MyApp', [])
.run(function ($templateCache, $route, $http) {
var url;
for(var i in $route.routes)
{
if (url = $route.routes[i].templateUrl)
{
$http.get(url, {cache: $templateCache});
}
}
})
if you wrap each template in a script tag, eg:
<script id="about.html" type="text/ng-template">
<div>
<h3>About</h3>
This is the About page
Its cool!
</div>
</script>
Concatenate all templates into 1 big file. If using Visual Studio 2013,Download Web essentials - it adds a right click menu to create an HTML Bundle
Add the code that this guy wrote to change the angular $templatecache service - its only a small piece of code and it works :-)
https://gist.github.com/vojtajina/3354046
Your routes templateUrl should look like this:
$routeProvider.when(
"/about", {
controller: "",
templateUrl: "about.html"
}
);
Related
I have index.html main file and partial view1.html and I use ng-route. So I want controller view1.js to be loaded only when view1.html is accessed. So I successfully loaded the file using resolve directive. Since javascript loads in background angular starts to parse view1.html and I get:
[ng:areq] Argument 'SimpleController2' is not a function, got undefined
How do I to tell angular that a new controller has been added, and it should parse view1.html only after applying the controller.
Check this out
main.js
var demoApp = angular.module('demoApp', ['ngRoute']);
demoApp.config(function ($routeProvider) {
$routeProvider
.when('/view1', {
controller: 'SimpleController1',
templateUrl: 'View1.html',
resolve: {
lol : function get() {
console.log('file is being loaded');
var fileRef = document.createElement('script');
fileRef.setAttribute("type", "text/javascript");
fileRef.setAttribute("src", "view1.js");
document.getElementsByTagName("head")[0].appendChild(fileRef);
fileRef.onload = function () {
console.log('file loaded');
}
}
}
})
.when('/view2',
{
controller: 'SimpleController',
templateUrl: 'View2.html'
})
.otherwise({redirectTo: '/view1'});
});
console.log('config has been added');
controller.js
console.log("file parsed");
demoApp.filter('myFilter', function ($sce) {
return function (input, isRaw) {
input = input.replace(/a/g, 'b');
return $sce.trustAsHtml(input);
};
});
demoApp.controller("SimpleController1", function ($scope, simpleFactory) {
$scope.names = [
{name: 'Nick', city: 'London'},
{name: 'Sick', city: 'Tokio'},
{name: 'Brick', city: 'cellar'}
];
});
I'm new to angular I tried this, this (how to apply files)
and this (gave up with applying $controllerProvider)
this (didn't succeed either) and this (couldn't make the whole thing work together) I'm not even sure that those described my needs. Please give me a clue what post I should dive deeper.
You can't check the existence of the controller without dry-running it with $controller and catching an exception, which is terrible thing to do.
Even then you will have hard time to register a new controller, because after config phase app.controller can't be used, and $controllerProvider.register is available only in config blocks.
You may look at existing solutions for lazy loading, i.e. ocLazyLoad. Here is how it manages routes.
I am using templateUrl to display specific php pages in my webpage. Now I wish to scrap the individual php pages and display code with variables passed to it. What is the easiest way to get back to this?
var AppModule = angular.module('App', ['ngAnimate', 'ngRoute']);
AppModule.config(function($routeProvider) {
$routeProvider
.when('/page:pageNumber', {
templateUrl: function ($routeParams) {
return '/app/..../assets/html/page' + $routeParams.pageNumber + '.php';
},
controller: "PageCtrl"
})
.otherwise({
redirectTo: "/page1"
});
});
AppModule.controller("ViewCtrl", function($scope, $timeout) {
$scope.$on("$routeChangeSuccess", function(event, current, previous) {
...stuff...
});
});
Use scripts via text/ng-template, which allows you to write your templates inline while declaring a url to access them by. The following code can go directly in your index.html, and if your config is set to show '/my-template.html', the inline template will be output right in the ng-view above it.
<ng-view />
<script type="text/ng-template" id="/my-template.html">
template goes here
</script>
Then in your config:
.when('/', {
templateUrl: '/my-template.html'
});
Here's a little more info from the Angular docs:
https://docs.angularjs.org/api/ng/directive/script
And lastly, this technique is demonstrated in one of the TodoMVC examples for Angular:
View: https://github.com/tastejs/todomvc/blob/gh-pages/examples/angularjs/index.html
Config: https://github.com/tastejs/todomvc/blob/gh-pages/examples/angularjs/js/app.js
I am trying to create an Angular Dynamic Routing. My routing is like this:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', { templateUrl: 'partials/blank.html' });
$routeProvider.when('/:name', { templateUrl: 'partials/blank.html', controller: PagesController });
$routeProvider.otherwise({redirectTo: '/'});
}]);
Here I am using $http to get a template file inside a controller and compile it to a div id like this:
function PagesController($scope, $http, $route, $routeParams, $compile) {
$route.current.templateUrl = 'partials/' + $routeParams.name + ".html";
$http.get($route.current.templateUrl).then(function (msg) {
$('#view-template').html($compile(msg.data)($scope));
});
}
In the template view, I have a div like this:
<div id="view-template" ng-view></div>
I thought the above code will compile and add the html data to the div but I am receiving the error that says: $ is not a function. What have I got wrong here?
EDIT: After the help from the comments and answers below
SOLUTION:: I was playing around with this a bit more and I went with another solution for this. I added the $route.current.templateUrl to the $scope.theTemplateUrl and then used ng-include in the template file. That did the trick and I also dont need to use the jquery $ function to manipulate the DOM.
Please make a fiddle. The limited scope of this snippet inhibits help :)
By just looking at what you are doing I can only make a few recommendations. But I think your issue lies in .html().
Stop using jQuery while you learn Angular.
Use $scope to change content on page. Instead of
$('#view-template').html($compile(msg.data)($scope));
do this
$scope.viewTemplate = msg.data
then use angular in your view :)
Only use the controller to coordinate the flow of information. There should not be and DOM manipulation happening here. The DOM should reflect a state of the controller.
Define routes in your app config. This is not correct.
$route.current.templateUrl = 'partials/' + $routeParams.name + ".html";
I have some example site in my github repo that you can look at if you want to see a few full sites working: https://github.com/breck421
It seems like you have missed some key parts of Angular. Make sure you take your time and learn it right. It will make you life much easier later.
Thanks,
Jordan
Added for a route provider example:
MyApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'js/views/index.html',
controller: 'AppController',
activeTab: 'home'
})
.when('/home', {
templateUrl: 'js/views/index.html',
controller: 'AppController',
activeTab: 'home'
})
.when('/thing1', {
templateUrl: 'js/views/thing1.html',
controller: 'Thing1Controller',
activeTab: 'thing1'
})
.otherwise({redirectTo: 'home'});
}]);
Then use links like this: Components
EDIT Adding a compile directive per request:
angular.module('CC.directive.Compile', [], function($compileProvider) {
$compileProvider.directive('compile', ['$compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
return scope.$eval(attrs.compile);
},
function(value) {
element.html(value);
$compile(element.contents())(scope);
}
);
};
}]);
});
The $ function is defined by jQuery, not angular. Make sure that you have included the jQuery library in order to use $
Could you help me to understand how to load controller in the example below before the view? It looks like the view is loaded just immediately while the controller is not loaded yet.
//app.js
$stateProvider.state('index', {
url: "/",
views: {
"topMenu": {
templateUrl: "/Home/TopMenu",
controller: function($scope, $injector) {
require(['controllers/top-menu-controller'], function(module) {
$injector.invoke(module, this, { '$scope': $scope });
});
}
}
}
});
//top-menu-controller.js
define(['app'], function (app) {
app.controller('TopMenuCtrl', ['$scope', function ($scope) {
$scope.message = "It works";
}]);
});
//Home/TopMenu
<h3>TopMenu</h3>
<div ng-controller="TopMenuCtrl">
{{message}}
</div>
I created working plunker here.
Let's have this index.html:
<!DOCTYPE html>
<html>
<head>
<title>my lazy</title>
</head>
<body ng-app="app">
#/home // we have three states - 'home' is NOT lazy
#/ - index // 'index' is lazy, with two views
#/other // 'other' is lazy with unnamed view
<div data-ui-view="topMenu"></div>
<div data-ui-view=""></div>
<script src="angular.js"></script> // standard angular
<script src="angular-ui-router.js"></script> // and ui-router scritps
<script src="script.js"></script> // our application
<script data-main="main.js" // lazy dependencies
src="require.js"></script>
</body>
</html>
Let's observe the main.js - the RequireJS config:
require.config({
//baseUrl: "js/scripts",
baseUrl: "",
// alias libraries paths
paths: {
// here we define path to NAMES
// to make controllers and their lazy-file-names independent
"TopMenuCtrl": "Controller_TopMenu",
"ContentCtrl": "Controller_Content",
"OtherCtrl" : "Controller_Other",
},
deps: ['app']
});
In fact, we only create aliases (paths) for our ControllerNames - and their Controller_Scripts.js files. That's it. Also, we return to require the app, but we will in our case use different feature later - to register lazily loaded controllers.
what does the deps: ['app'] mean? Firstly, we need to provide file app.js (the 'app' means find app.js) :
define([], function() {
var app = angular.module('app');
return app;
})
this returned value is the one we can ask for in every async loaded file
define(['app'], function (app) {
// here we would have access to the module("app")
});
How will we load controllers lazily? As already proven here for ngRoute
angularAMD v0.2.1
angularAMD is an utility that facilitates the use of RequireJS in AngularJS applications supporting on-demand loading of 3rd party modules such as angular-ui.
We will ask angular for a reference to $controllerProvider - and use it later, to register controllers.
This is the first part of our script.js:
// I. the application
var app = angular.module('app', [
"ui.router"
]);
// II. cached $controllerProvider
var app_cached_providers = {};
app.config(['$controllerProvider',
function(controllerProvider) {
app_cached_providers.$controllerProvider = controllerProvider;
}
]);
As we can see, we just created the application 'app' and also, created holder app_cached_providers (following the angularAMD style). In the config phase, we ask angular for $controllerProvider and keep reference for it.
Now let's continue in script.js:
// III. inline dependency expression
app.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$urlRouterProvider
.otherwise("/home");
$stateProvider
.state("home", {
url: "/home",
template: "<div>this is home - not lazily loaded</div>"
});
$stateProvider
.state("other", {
url: "/other",
template: "<div>The message from ctrl: {{message}}</div>",
controller: "OtherCtrl",
resolve: {
loadOtherCtrl: ["$q", function($q) {
var deferred = $q.defer();
require(["OtherCtrl"], function() { deferred.resolve(); });
return deferred.promise;
}],
},
});
}
]);
This part above shows two states declaration. One of them - 'home' is standard none lazy one. It's controller is implicit, but standard could be used.
The second is state named "other" which does target unnamed view ui-view="". And here we can firstly see, the lazy load. Inside of the resolve (see:)
Resolve
You can use resolve to provide your controller with content or data that is custom to the state. resolve is 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 $stateChangeSuccess event is fired.
With that in our suite, we know, that the controller (by its name) will be searched in angular repository once the resolve is finished:
// this controller name will be searched - only once the resolve is finished
controller: "OtherCtrl",
// let's ask RequireJS
resolve: {
loadOtherCtrl: ["$q", function($q) {
// wee need $q to wait
var deferred = $q.defer();
// and make it resolved once require will load the file
require(["OtherCtrl"], function() { deferred.resolve(); });
return deferred.promise;
}],
},
Good, now, as mentioned above, the main contains this alias def
// alias libraries paths
paths: {
...
"OtherCtrl" : "Controller_Other",
And that means, that the file "Controller_Other.js" will be searched and loaded. This is its content which does the magic. The most important here is use of previously cached reference to $controllerProvider
// content of the "Controller_Other.js"
define(['app'], function (app) {
// the Default Controller
// is added into the 'app' module
// lazily, and only once
app_cached_providers
.$controllerProvider
.register('OtherCtrl', function ($scope) {
$scope.message = "OtherCtrl";
});
});
the trick is not to use app.controller() but
$controllerProvider.Register
The $controller service is used by Angular to create new controllers. This provider allows controller registration via the register() method.
Finally there is another state definition, with more narrowed resolve... a try to make it more readable:
// IV ... build the object with helper functions
// then assign to state provider
var loadController = function(controllerName) {
return ["$q", function($q) {
var deferred = $q.defer();
require([controllerName], function() {deferred.resolve(); });
return deferred.promise;
}];
}
app.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
var index = {
url: "/",
views: {
"topMenu": {
template: "<div>The message from ctrl: {{message}}</div>",
controller: "TopMenuCtrl",
},
"": {
template: "<div>The message from ctrl: {{message}}</div>",
controller: "ContentCtrl",
},
},
resolve : { },
};
index.resolve.loadTopMenuCtrl = loadController("TopMenuCtrl");
index.resolve.loadContentCtrl = loadController("ContentCtrl");
$stateProvider
.state("index", index);
}]);
Above we can see, that we resolve two controllers for both/all named views of that state
That's it. Each controller defined here
paths: {
"TopMenuCtrl": "Controller_TopMenu",
"ContentCtrl": "Controller_Content",
"OtherCtrl" : "Controller_Other",
...
},
will be loaded via resolve and $controllerProvider - via RequireJS - lazily. Check that all here
Similar Q & A: AngularAMD + ui-router + dynamic controller name?
On one project I used lazy loading of controllers and had to manually call a $digest on the scope to have it working. I guess that this behavior does not change with ui-router.
Did you try that ?
define(['app'], function (app) {
app.controller('TopMenuCtrl', ['$scope', function ($scope) {
$scope.message = "It works";
$scope.$digest();
}]);
});
Does angular support dynamic routing at all?
Maybe some trick like this:
$routeProvider.when('/:ctrl/:action',
getRoute($routeParams.ctrl,$routeParams.action))
function getRoute(ctrl, action){
return {
templateUrl: ctrl+"-"+action+".html"
controller: 'myCtrl'
}
}
Please help me, I need to get templateUrl based out of routeParams
This is a late answer but I came across this problem myself, but it turns out that the solution by Dan conflicts with ngAnimate classes on the ngView directive, and the view is shown but the ng-leave animation will immediately be applied and hide the view opened with his dynamic routing.
I found the perfect solution here, and it's available in 1.1.5 +
In the $routeProvider, the templateUrl value can be a function, and is passed the route parameters:
app.config(function ($routeProvider) {
$routeProvider
.when('/:page', {
templateUrl: function(routeParams){
return '/partials/'+routeParams.page+'.html';
}
})
});
Though the controller can't be given as a function so my solution is to give it in the template html as per usual with ng-controller="HomeCtrl".
Using this solution we can route by convention in Angular.
I hope this helps others who weren't keen on manually adding every route to the routeProvider.
You want to bring it down to the controller level.
In this example, I am overriding entire pages as well as partials by subdomain:
app.js
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/', {
template: 'home'
});
$routeProvider.when('/contact', {
template: 'contact'
});
$routeProvider.otherwise({redirectTo: '/'});
}])
controllers.js
controller('AppController', ['$scope','Views', function($scope, Views) {
$scope.$on("$routeChangeSuccess",function( $currentRoute, $previousRoute ){
$scope.page = Views.returnView();
});
$scope.returnView = function(partial){
return Views.returnView(partial);
}
}])
services.js
factory('Views', function($location,$route,$routeParams,objExistsFilter) {
var viewsService = {};
var views = {
subdomain1:{
'home':'/views/subdomain1/home.html'
},
subdomain2:{
},
'global.header':'/views/global.header.html',
'global.footer':'/views/global.footer.html',
'home':'/views/home.html',
'home.carousel':'/views/home.carousel.html',
'contact':'/views/contact.html',
};
viewsService.returnView = function(partial) {
var y = (typeof partial === 'undefined')?$route.current.template:partial;
var x = $location.host().split(".");
return (x.length>2)?(objExistsFilter(views[x[0]][y]))?views[x[0]][y]:views[y]:views[y];
};
viewsService.returnViews = function() {
return views;
};
return viewsService;
}).
filters.js
filter('objExists', function () {
return function (property) {
try {
return property;
} catch (err) {
return null
}
};
});
index.html
<!doctype html>
<html lang="en" ng-controller="AppController">
<body>
<ng-include src="returnView('global.header')"></ng-include>
<ng-include src="page"></ng-include>
<ng-include src="returnView('global.footer')"></ng-include>
</body>
</html>