Can one server serve 2 angularjs modules / routings? - javascript

(I re-edited my initial question to better explain the context.)
I have a mean-stack web site built with angular-ui-router and html5mode. routes/index.js contains the following code, and it is views/index.html which has <ui-view></ui-view> and is the entry point of all the pages. As a result, https://localhost:3000/XXXX in a browser will remain the same (rather than adding #) and show the corresponding content based on the router.
router.get('*', function(req, res) {
console.log("router.get *");
res.sendfile('./views/index.html');
});
Now, because of this problem, I want to have views/addin.html that contains office.js and another router, such that the site serves a set of urls https://localhost:3000/addin/XXXX, and I don't mind if it is html5mode or not (a url can contain # somewhere). To this end, I added one block for addin in routes/index.js:
router.get('/addin/*', function (req, res) {
console.log("router.get /addin/*");
res.sendfile('./views/addin.html')
});
router.get('*', function(req, res) {
console.log("router.get *");
res.sendfile('./views/index.html');
});
And here is views/addin.html:
<html>
<head>
<title>addinF</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.js"></script>
</head>
<body ng-app="addinF">
addin content
<ui-view ng-cloak></ui-view>
</body>
<script>
var addinApp = angular.module('addinF', ['ui.router'])
addinApp.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('addinNew', {
url: '/addin/new',
template: "new page"
})
.state('addinHome', {
url: '/addin/home',
template: "home page"
})
}]);
</script>
</html>
However, loading https://localhost:3000/addin/new or https://localhost:3000/addin/home just shows addin content and does not show new page or home page in console; it did not raise any error either.
Could anyone tell me what's missing? Can one server serve 2 angularjs modules or routings?

Just add initial redirection:
appAddin.config(['$urlRouterProvider', function ($urlRouterProvider) {
$urlRouterProvider.otherwise("/addin/new");
}])
There is a working plunker

Related

AngularJS - Error: [$compile:tpload] Failed to load template (Spring Boot)

I've checked similar questions online for this, but none of them satisfied my issue. I'm building a simple SPA with angularjs 1.6.4 and spring boot.
Error: Error: [$compile:tpload] Failed to load template: test.html
(HTTP status: 404 )
It is working fine when I don't add ngRoute to the code & it fails to load the html template when I try to run it with routes. My backend is springboot with thymeleaf template (not sure if this is causing issue of some sort) because running the UI code alone in xampp server provides the routing correctly.
I initially thought in the templateUrl I've mentioned the wrong path. Here is how my folder structure looks.
To reduce strain I've added my entire JS code in single index.html as a tag here.
<!DOCTYPE HTML>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
</head>
<body ng-app="app">
<ng-view></ng-view>
<script>
// Creating Routes (ngRoute)
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.when("/", {
templateUrl : 'test.html',
controller : 'postcontroller'
}).when("/uploadPath", {
templateUrl : 'test1.html',
controller : 'uploadPath'
}).otherwise({
redirectTo : "/"
});
});
// Creating controller
app.controller("uploadPath", function($scope, $location) {
$scope.passthrough = function() {
$location.path('/uploadPath')
};
});
app.controller('postcontroller', function($scope, $http, $location) {
// be used to decide for showing PostResults
$scope.postDivAvailable = false;
// be used for decide for showing GetResults
$scope.getDivAvailable = false;
$scope.submitForm = function() {
// post URL
var url = $location.absUrl() + "api/config/save";
// prepare headers for posting
var config = {
headers : {
'Content-Type' : 'application/json',
'Accept' : 'application/json'
}
}
// prepare data for post messages
var data = {
xx: $scope.xx,
yyyy: $scope.yyyy,
zzzz: $scope.zzzzz
};
// do posting
$http.post(url, data, config).then(function(response) {
$scope.postDivAvailable = true;
$scope.postCust = response.data;
}, function error(response) {
$scope.postResultMessage = "Error Status: " + response.statusText;
});
// reset data of form after posting
$scope.xx= '';
$scope.yyyy= '';
$scope.zzzzz= '';
}
});
</script>
</body>
</html>
In the test.html file I just have a form with three fields. The problem here is that when I load localhost:8080/ the test.html itself is not loading & it throws this error.
Error: [$compile:tpload] Failed to load template: test.html (HTTP status: 404 )
any help is much appreciated!!
This is the fix I did which solved the problem. I'm not sure If Im understanding is correct on this question. So kindly improve this answer if someone has better understanding on the problem.
Basically the Spring Boot Thymeleaf templating engine takes the .html file from the src/main/java folder structure. But when the routes are added, the Spring Boot application expects all the .html files to be inside the webapp folder. i.e src/main/webapp.
After placing the .html files inside the webapp folder solved the issue. There were no issues in the angularJS routing codes.

Could not get the pages while refreshing the browser using ui-router Angular.js

I need some help.I am facing some issues. I could not get the pages after refreshing again using Angular.js. I am explaining my code below.
route.js:
var app=angular.module('demo',['ui.router']);
app.run(function($rootScope, $state) {
$rootScope.$state = $state;
});
compliance.config(function($stateProvider, $urlRouterProvider,$locationProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/', {
url: '/',
templateUrl: 'View/demo1.html',
controller: 'demoController'
})
.state('demo2', {
url: '/demo2',
templateUrl: 'View/demo2.html',
controller: 'demo2Controller'
})
$locationProvider.html5Mode({
enabled: true,
requireBase: true
});
});
index.html:
<div ui-view></div>
demo1.html:
demoController.js:
$scope.goToAuditDetailPage=function(){
$state.go('demo2',{}, { reload: true });
}
Here when user will open the link http://localhost/NABH/ the demo1.html page will come and inside that page there is one click event, when user will click on that link the demo2.html page is coming and the URL is http://localhost/NABH/demo2. But In this case when user will refreshing that link http://localhost/NABH/demo2 again this The requested URL /NABH/demo2 was not found on this server. error is coming. Here I need after refreshing also that page should work as per expected.Please help.
You are using html5mode with your routes, therefore the browser changes the routes of your app as they are come from the server, when ever the user press on the refresh button, the browser sends a request with your client route, and your server doesn't aware of it.
One of the simplest solution is to make the server "answer" to all the routes with your client app, in that way, the request with your client rout with be answered with index.html shell (as it answered when you navigate to /), and the client app will check the current route and render the proper page (it's done automatically).

Node.js - Redirecting in Express with a Master / Detail Page

I am learning Node.js. I am in the process of building a basic app for the sake of learning. At this time, I'm trying to do a master/detail page. Here is the master page.
/views/master.ejs
<html>
<body>
[items would go here]
add new
</body>
</html>
The user will see this page when they visit '/'. When they click the "add new" link, I will take them to "/new". The code for the view is here:
/views/detail.ejs
<html>
<body>
<form id="myForm" method="post" action="/new">
<button type="submit">Submit</button>
</form>
</body>
</html>
I have these successfully working. However, when a user clicks submit, I'm not sure how to redirect them back to the "/" view. At this time, my routing code looks like this:
var router = require('express').Router();
/* GET the master page. */
router.get('/', function(req, res) {
res.render('master', { });
});
/* GET the new page */
router.get('/new', function(req, res) {
res.render('detail', { });
});
/* POST new item */
router.post('/new', function(req, res) {
console.log('creating item...');
// The following line just shows "undefined" in the browser"
// I don't know if 1) Its correct or 2) If I should do it some other way
res.redirect(200, '/', { });
});
How do I handle loading views in a master-detail page scenario?
Thanks!
Have you tried redirecting without passing a view model? For example:
res.redirect('/projects/setup/website/details');
None of the samples in the documentation show a view model being passed.
It looks like you're trying to redirect in a POST. If you would like to render the home page after your POST request, simply render the expected result.
/* POST new item */
router.post('/new', function(req, res) {
// do server stuff ...
res.render('master');
});
I think use below code may helpful.
router.post('/new', function(req, res) {
console.log('creating item...');
res.redirect('/'); // if you don`t specify status defaults to 302 found
});
see this link : http://expressjs.com/api.html#res.redirect

How get data with angular from the backend and send it with node.js for the frontend?

I'm changing my node.js application, i was using EJS template engine and now i want use angular.
For this i already install angular and is working good, but now i want get my data, and for this i'm using the $http service:
(function($) {
app.controller('EventCtrl', ['$scope', '$http', function($scope, $http){
$scope.data;
$http.get('/data').
success(function(data, status, headers, config) {
$scope.data = data;
}).
error(function(data, status, headers, config) {
$scope.data = data;
});
}]);
}(jQuery));
And i'm sending the data in the backend:
restAPI.GET(options).then(function (result) {
res.render('data/index.html', {
event: result,
});
}).then(undefined, function (error) {
console.log(error);
});
But its returning the HTML from the same page that i'm using the controller. What am i doing wrong here??
What is returning:
<!DOCTYPE html> <html ng-app="app"> <head> <title> Testando Angular </title> </head> <body> <div ng-controller="EventCtrl"> {{data}} </div> </body> <script type="text/javascript" src="/lib/jquery/dist/jquery.min.js"></script> <script type="text/javascript" src="/lib/angular/angular.min.js"></script> <script type="text/javascript" src="/app.js"></script> <script type="text/javascript" src="/controllers/EventCtrl.js"></script> </html>
You need to have node serve up the page which angular lives on.
(This is using just an example using express)
Something like this:
app.get('/', function(req, res) {
res.sendFile('../public/index.html');
res.end();
});
Then you need to set up routes for angular to query so it can get data:
app.get('/api/data', function (req, res) {
//Get some data here however you do that
res.json(data) //Send your data back to angular in the callback of your database query ( or whatever you are doing )
}
You use res.render() to send a page. You don't want to send a page. You just want to send data if you are using the $http.get request shown above. Fetch your data and send it with res.json(data)
If you need some insight into how all the pieces fit together, I would recommend working through the following tutorial:
Setting Up a MEAN Stack SPA

Angular load partial based on data sent by server

I have an <ng-view></ng-view> that is filled with a partial html file when a button is clicked i.e Sign In
myApp.js
var myApp = angular.module("myApp", ['ngRoute']);
//Define Routing for app
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/signin', {
templateUrl: 'signin.ejs'
}).
when('/signup', {
templateUrl: 'signup.ejs'
}).
when('/myAccount', {
templateUrl: 'myAccount.ejs'
}).
otherwise({
//home page
});
}]);
What I want to know is, how can fill this ng-view based on data that is sent by the server. For example, if the server renders the index.html with data {page: '/signin'} how can I let Angular know that I want to to populate the ng-view with 'signin.ejs'??
Any help is appreciated. Thank you!!
EDIT:
I have someone logged in to the site and on a page I provide a "switch account" button. So what I want to do is, when that is clicked, post to the server /logout route so the session can be cleared, and then change the page to the signin page (partial html file) and populate the username field with the account that they are switching to
Your ejs needs to be rendered by nodejs so you need to apply your the routing there.
You need to come up with a way to identify the route path like '/partials/:filename'
app.route('/partials/:filename').get(funcs.partials);
Then you handle the request and render your ejs or plain you just send(html) and you use the path module to locate and manipulate the url string.
exports.partials = function(req, res, next, filename) {
res.render(filename, vars);
};
Then your angular is like, though signin is probably not the best example.
$routeProvider.
when('/signin', {
templateUrl: '/partials/signin'
})

Categories

Resources