How to run a multi-route angular app in a single page - angularjs

Imagine we have an AngularJs app (witten in multiple controllers, services, directive and run method) for multiple routes using $routeProvider. and now we need to use the same application in a single page. meaning that templates of different routes should now be visible in one page at the same time.
I can't use different iframes because then it's hard to access the $scopes of those controllers from the wrapper application.
Is this possible without the use of iframes?

What you are looking for is ng-include and ng-controller. Using ng-include, You can insert a html into the block containing it and using ng-controller, you can insert a controller for the same block. I would prefer not to use iframes as it is a bad practice and you will not be able to access scope and a lot of features that are native to angular.
EDIT : Since, you are using the run() function you can try the below approach :
Keeping the routeProvider same, you can move the contents of you html template files into script tags on you index.html like so :
<script type="text/ng-template" id="one.tpl.html">
//Your html template code goes here
</script>
<script type="text/ng-template" id="two.tpl.html">
//Your html template code goes here
</script>
In you app.js :
$routeProvider.
when('/', {
templateUrl: 'one.tpl.html', //points to the content of the script tag in your index.html file
controller: 'onetplCtrl'
}).
when('/edit',{
templateUrl:'two.tpl.html', //points to the content of the script tag in your index.html file
controller:'twotplCtrl'
}).
otherwise({
redirectTo: '/'
});

Related

navigating to a different page within the application using angular js

This question might sound very generic to some of you but as a newbie i am having trouble in this. Its evident to use ng-view within the home page in order to display other html files within the page but how should i redirect to a new page present in the web app. I mean how to route to completely different web page in a multipage web application.
Import AngularJs-Route File
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
Then you must add the ngRoute as a dependency in the application module:
var app = angular.module("myApp", ["ngRoute"]);
Use the $routeProvider to configure different routes in your application:
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm"
})
.when("/red", {
templateUrl : "red.htm"
})
.when("/green", {
templateUrl : "green.htm"
})
.when("/blue", {
templateUrl : "blue.htm"
});
});
STructure Your HTML
<body ng-app="myApp">
<p>Home</p>
Red
Green
Blue
<div ng-view></div>
</body>
For nested views you can use https://github.com/angular-ui/ui-router
Follow https://github.com/angular-ui/ui-router/wiki/Nested-States-&-Nested-Views for reference
Try searching angular ui-roter how its works and its mechanism . Since angular is a single page application your app needs to be on one base template then expand from their. From base template route in different page but if you want to route to different application use normal hyper link or ui-serf . Go though u-router basic. Also look into ui-serf .

How to preload a template in my ui-view

I want to preload a template in my div using ui-router.
This is my template.html file which is located in /templates folder.
// its location is templates/template1.html
<div>
Template 1
</div>
The .config function in angularjs has the following code which includes the states. Here template1 is the child state of the state1
.state('state1',{
url:'/state1',
templateUrl:'templates/state1.html',
controller: 'state1Controller',
})
.state('state1.template1',{
templateUrl: 'templates/template1.html'
})
Template1 is loaded when i press a button, but i want the template to be preloaded. What can i do to attain my desired result?
Declarative way: Put all your template into a script tag with type as text/ng-template:
<script type="text/ng-template" id="templateId.html">
<p>This is the content of the template</p>
</script>
Code way: Use $templateCache for this.
In state1Controller, load your template and put it into cache like this:
$templateCache.put('templateId.html', 'This is the content of the template');
Or load it with http:
$http.get('templates/template1.html').then(function(template){
$templateCache.put('templateId.html', template);
})
Then in your router definition, put templateId.html as value of templateUrl
.state('state1.template1',{
templateUrl: 'templateId.html'
})
and any time you request templateId.html, angular will automatically find template in $templateCache before sending request to server.

Angular ngRoute not working on reload with ngInclude

In case anyone else runs into the same issue. While trivial to some, it was not trivial for me.
The problem:
When the page loads ngRoute fails to load the shell (landing page) template when using ng-view inside ng-include.
However if we start navigating around the pages including navigating back to landing page then the template loads just fine. It is as if the first time the page loads it completely skips loading the landing template.
The setup:
Somewhere at the bottom of index.html's body:
<script src="angular-route.js"></script>
Somewhere in index.html template
<div ng-include="'root-shell.html'"></div>
Somewhere in root-shell.html template
<div ng-view></div>
The JS:
(function (/* IIFE enclosed code*/) {
angular('myApp', [$routeProvider]);
angular('myApp').config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'root-shell.html',
controller: 'RootShellController', // optional
controllerAs: 'rootShellCtrl' // optional
}).
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController', // optional
controllerAs: 'aboutCtrl' // optional
}).
otherwise({
redirectTo: '/'
});
});
})(/* IIFE invoke*/);
Why the problem?
Because if ng-view instantiation is delayed (through ng-include) then the $route instantiation is delayed as well. This means that $route will miss the location change event.
The fix:
Force a reload of the $route service.
angular('myApp').run(['$route', function($route) {
$route.reload();
}]);
Why does it work?
Because of angular's order of execution:
app config
app run
directive setup
directive compile
app controller
directive link
** Data resolve called **
new route's controller
and the run block:
Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
Disclaimer:
I am fairly new to Angular, therefore if I've misunderstood and/or misrepresented a concept then by all means chime in.

Using ng-route with Google-Apps-Script or some means of rendering a partial html view

I am trying to get ng-route working with a google-apps-script web app. I have managed to get basic angular.js functionality working with google-apps-script, but I can't seem to get ng-route to work. I have placed ng-view tags inside a page and have included a separate JavaScript page that contains the routeProvider function.
The ng-view never gets rendered and as far as I can make out the routeProvider does not get called.
Can anyone offer any advice on using ng-route with google-apps-script or suggest another way of rendering a partial html page with google-apps-script
Any answers greatly appreciated.
Have simplified my code and added below:
Code.gs
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Index');
// Build and return HTML in IFRAME sandbox mode.
return template.evaluate()
.setTitle('Web App Window Title')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getScriptUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
index.html
<!-- Use a templated HTML printing scriptlet to import common stylesheet. -->
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
<html>
<body ng-app="myApp">
<h1>NG View</h1>
<ng-view></ng-view>
<p>angular check {{'is' + 'working!'}}</p>
<? var url = getScriptUrl();?>
<p id="urlid"><?=url?></p>
</body>
</html>
<!-- Use a templated HTML printing scriptlet to import JavaScript. -->
<?!= HtmlService.createHtmlOutputFromFile('JavaScript').getContent(); ?>
Javascript.html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="https://code.angularjs.org/1.3.15/angular-route.js"> </script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<script>
angular.module('myApp', ['ngRoute'])
.config(function($routeProvider){
console.log('routeProvider config');
var url = document.getElementById("urlid").innerHTML;
console.log('routeProvider config->' +url);
$routeProvider.when("/",
{
templateUrl: url+"?page=_app.html",
controller: "AppCtrl",
controllerAs: "app"
}
);
})
.controller('AppCtrl', function() {
var self = this;
self.message = "The app routing is working!";
});
</script>
_app.html
<div>
<h1>{{ app.message }}</h1>
</div>
When this runs angular check {{'is' + 'working!'}} works fine, but the ng-view does not get rendered the java console shows:
Error: [$sce:insecurl] Blocked loading resource from url not allowed by $sceDelegate policy.
The first obstacle is "sce"
$sce is a service that provides Strict Contextual Escaping services to AngularJS.
Refer link https://docs.angularjs.org/api/ng/service/$sce#trustAsResourceUrl
For the purpose of investigation, I disabled sce (this is not recommended, though)
$sceProvider.enabled(false);
Now the error is shifted to XMLHttpRequest cannot load... No 'Access-Control-Allow-Origin' header is present on the requested resource.
XHR requests to the Google Apps Script server are forbidden
Refer link https://developers.google.com/apps-script/guides/html/restrictions
Google Apps is delivering the files from a different origin than the scripts.google.com and angular js client code is not able to fetch the partial htmls from the same origin.
I guess approach of ng-view is not feasible given the restrictions placed by google apps.
Here is the final modified code
<script>
angular.module('myApp', ['ngRoute'])
.config(function($routeProvider,$sceProvider){
$sceProvider.enabled(false);
console.log('routeProvider config');
var url = document.getElementById("urlid").innerHTML;
console.log('routeProvider config->' +url);
$routeProvider.when("/",
{
templateUrl: url+"?page=_app.html",
controller: "AppCtrl",
controllerAs: "app"
}
);
})
.controller('AppCtrl', function() {
var self = this;
self.message = "The app routing is working!";
});
</script>
There has been some time since the question, but I'll post a reply either way.
If your partial html page is not too complicated and big, you can use template instead of templateUrl in the routeProvider, plus create a variable with the html you want to show. Something like this below:
var partial_page = "<span>partial page</span>"
$routeProvider.when("/",
{
template: partial_page,
controller: "AppCtrl",
controllerAs: "app"
}
It worked for me, but I wouldn't advise doing so for a complicated partial page as it may become difficult to read the code

How to load language-specific templates in AngularJS?

I have a route defined as
$routeProvider.when('/:culture/:gameKey/:gameId/closed', { templateUrl: '/templates/tradingclosed', controller: TradingClosedCtrl });
I would like angular to include the "culture" parameter when requesting the template somehow, so I can serve a translated template.
Is this possible?
If I'm reading this correctly you'd like to somehow use the culture parameter from the url route to determine which location to retrieve your template.
There may be a better way but this post describes retrieving the $routeParams inside a centralized controller with ng-include to dynamically load a view.
Something similar to this:
angular.module('myApp', []).
config(function ($routeProvider) {
$routeProvider.when('/:culture/:gameKey/:gameId/closed', {
templateUrl: '/templates/nav/urlRouter.html',
controller: 'RouteController'
});
});
function RouteController($scope, $routeParams) {
$scope.templateUrl = 'templates/tradingclosed/' + $routeParams.culture + '_template.html';
}
With this as your urlRouter.html:
<div ng-include src="templateUrl"></div>
You can define the controller you want to load in your views using ng-controller and access the $routeParams for the additional route parameters:
<div ng-controller="TradingClosedCtrl">
</div>
I've posted similar question with working Plnkr example of solution like #Gloopy suggested.
The reason why you can't implement that without ng-include is that routing is done in 'configuration' block, where you can't inject any values (you can read about these blocks in Modules documentation, section Module Loading & Dependencies
If you want not to introduce new scope, you can replace ng-include with my stripped version of ng-include directive, that do absolutely same that ng-include does, but do not create new scope: source of rawInclude directive
Hope that solution will satisfy your use case.

Resources