Angularjs routing to # causing problems - javascript

Fairly new to angularjs, trying to make a single page application.
The default page to load should be a home page, and I also want a home button to route to this page.
Nav bar in HTML:
<html ng-app="app">
...
<ul class="nav navbar-nav navbar-center">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
...
<div ng-view></div>
in app.module.js:
var app = angular.module('app', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/home.html',
controller: 'main',
controllerAs: 'vm'
})
.when('/about', {
templateUrl: 'pages/about.html',
controller: 'about',
controllerAs: 'vm'
})
.when('/contact', {
templateUrl: 'pages/contact.html',
controller: 'contact',
controllerAs: 'vm'
});
});
app.controller('main', main);
app.controller('about', about);
app.controller('contact', contact);
function main() {
var vm = this;
vm.message = "Home page";
}
function about() { //stuff }
function contact() { //stuff }
When the page loads, everything displays correctly, and the url is http://localhost:8007/#/
My problem is that when I click Home, the url becomes http://localhost:8007/# and nothing displays. About and Contact both work as intended.
I know I can just change my Home button to have href="#/" but that feels like I am targeting the symptoms, not the problem. I feel like I really shouldn't have to do that.
I have tried adding .when('', { to app.module.js, but this does nothing.

Your home href will be Home which then translates to the path "/" you defined in $routeProvider.
Dont use href="#" anywhere in the app

Related

Angular Routing ngRoute fails to pull my other HTML files

So after reading here and there on MEAN, I decided to make my first MEAN application which is pretty small, all seems to work except the routeing to make my app a one-page app. Any help would be much appreciated!
app.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'main.html',
controller: 'mainController'
})
.when('/login', {
templateUrl: 'login.html',
controller: 'authController'
})
.when('/register', {
templateUrl: 'register.html',
controller: 'authController'
});
});
Anyway, I adopted a boilerplate navigation bar
<nav class="navbar-fluid navbar-default navbar-fixed-top">
<div class="container">
<a class="navbar-brand" href="#">IoT</a>
<p class="navbar-text">IoT</p>
<p class="navbar-right navbar-text" ng-hide="authenticated">Login or Register</p>
<p class="navbar-right navbar-text" ng-show="authenticated">Logout</p>
<p class="navbar-right navbar-text" ng-show="authenticated">Signed in as {{current_user}}</p>
</div>
</nav>
And, when I run it on localhost:3000, the homepage address I got instead is
http://localhost:3000/#!/
where I was expecting
http://localhost:3000/#/
And when I clicked on the 'register' link, the address I got is
http://localhost:3000/#!/#%2Fregister
where as I was expecting
http://localhost:3000/#/register
Is that normal? Maybe it's bcs of the version of Angular I was using?
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular-resource.min.js"></script>
It was all fine before, but then I stripped down the HTML and make the main page pull individual HTML pages one-by-one then this happened.
Change your links from <a href="#/login"> to <a href="#!/login">, <a href="#"> to <a href="#!"> etc..
I also have this issue but changing from a hash to hashbang resolves it for me.
Try this one. I'm not sure this will fix your issue. But please try this one.
Change your route provider by including default parameter.
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'main.html',
controller: 'mainController'
})
.when('/login', {
templateUrl: 'login.html',
controller: 'authController'
})
.when('/register', {
templateUrl: 'register.html',
controller: 'authController'
})
.otherwise({
redirectTo: '/'
});
});
and provide the links like Login
Try this one:
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'main.html',
controller: 'mainController'
})
.when('/login', {
templateUrl: 'login.html',
controller: 'authController'
})
.when('/register', {
templateUrl: 'register.html',
controller: 'authController'
})
.otherwise({
redirectTo: '/'
});
});
For Sign Out, You should use such as:
<p class="navbar-right navbar-text" ng-show="authenticated">Logout</p>
App.config(['$routeProvider', '$locationProvider', function config($routeProvider, $locationProvider) {
$locationProvider.hashPrefix('')
$routeProvider
.when('/', {
templateUrl: 'login.html',
controller: 'loginController'
})
.otherwise('/');
}]);
will work see https://docs.angularjs.org/api/ng/provider/$locationProvider

AngularJS Angular-Route on Ubuntu changing routes /#/ -> /#!/ links not working

Project works fine locally.
However after deploying it to an AWS Ubuntu instance, the routing does not seem to be working.
The home page of, www.lewisengelart.com/#/ loads with a bang as, www.lewisengelart.com/#!/
and if you try a link, the browser attempts to load
www.lewisengelart.com/#!/#%2Fabout rather than
www.lewisengelart.com/#/about.
Once again, this project works fine locally, I cannot figure out what is tripping it up on the ubuntu instance.
Has anyone encountered this problem before?
Here is app.js, the route config
var app = angular.module("App", ['ngRoute', 'ngAnimate']);
app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider){
$httpProvider.interceptors.push(
function($q, $location) {
return {
'responseError':function(rejection){
if (rejection.status == 401){
$location.url('/letmein');
}
return $q.reject(rejection);
}
};
});
$routeProvider
.when('/',{
templateUrl: 'partials/dashboard.html'
})
.when('/text',{
templateUrl: 'partials/text.html',
controller: 'textCtrl'
})
.when('/magnet',{
templateUrl: 'partials/magnet.html',
// controller: 'magnetCtrl'
})
.when('/gauge',{
templateUrl: 'partials/gauge.html',
// controller: 'gaugeCtrl'
})
.when('/animation',{
templateUrl: 'partials/animation.html',
controller: 'animationCtrl as ACtrl'
})
.when('/about',{
templateUrl: 'partials/about.html',
})
.when('/contact',{
templateUrl: 'partials/Contact.html',
})
.when('/letmein',{
templateUrl: 'partials/loginReg.html',
controller: 'adminCtrl'
})
.when('/add',{
templateUrl: 'partials/add.html',
controller: 'workCtrl'
})
.otherwise({
redirectTo: '/'
});
}])
And the home page partial with links
<div class="indexHeader col-md-3">
<h1>Lewis Engel</h1>
<div class="worksBox">
<a ng-href="/#/about"><span class="colorFive">About</span></a>
<span class="colorSix">Contact</span>
<span class="colorOne">Emergent Possibilities</span>
<span class="colorTwo">Emergence over Time</span>
<span class="colorThree">Magnetic Attractions</span>
<span class="colorFour">Meaningless Measures</span>
</div>
Per angular documentation.
docs.angularjs.org/guide/migration#commit-aa077e8.
Have to add
$locationProvider
and
appModule.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix('');
}]);
to override a new protocol in the updated version of Angular.

Controller not loading up

I have the following Index.html file (I put div with ng-view as well):
<ul ng-controller="myController">
<li>
Do it!
</li>
</ul>
routes config:
$routeProvider.when('/doit', {
templateUrl: 'partials/doit.html'
controller: 'myController'
});
$routeProvider.otherwise({
redirectTo: 'index.html'
});
Controller:
app.controller('myController', ['$scope', '$location', function ($scope, $location) {
$scope.name = "name";
alert($scope.name);
$location.path("/");
}]);
The weird thig is that after I click on the Do it! link, it goes to http://localhost:3000/#/doit.html (the code of myController executes after the click, I see the alert pop-up), and then I go back to http://localhost:3000/#/index.html (this is what I want, I put $location.path("/") in the controller.
However, this time, for some reason, the controller code doesn't execute. It only runs after I refresh the page, even though it is assigned to the unordered list. Could anyone help please?
Your routes config should be something like:
$routeProvider.
when('/', {
templateUrl: '/index.html',
controller: 'homeCtrl'
}).
when('/doit', {
templateUrl: 'partials/doit.html',
controller: 'myController'
}).
otherwise({
redirectTo: '/'
});
and you do not need to specify controller name at two places i.e. in the partial and in your route config, specifying at the config level should be sufficient.
The doit view should be the one which is loaded in the ng-view tag as it is a state of your application.

Angularjs routing fails on server when minification is turned on

I am currently building a Angularjs singel page application and i have run in to some odd error with my routing.
I have a nav bar with multiple options and all but one of them work correct.
This is my route provider.
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when("/index", {
templateUrl: "/App/Views/index.html",
controller: "IndexController"
})
.when("/log", {
templateUrl: "/App/Views/log.html",
controller: "LogController"
})
.when("/help", {
templateUrl: "/App/Views/help.html",
controller: "HelpController"
})
.when("/login", {
templateUrl: "/App/Views/login.html",
controller: "LoginController"
})
.when("/signup", {
templateUrl: "/App/Views/signup.html",
controller: "SignupController"
})
.when("/logout", {
templateUrl: "/App/Views/logout.html",
controller: "LogOutController"
})
.when("/user", {
templateUrl: "/App/Views/user.html",
controller: "UserController"
})
.otherwise({
redirectTo: "/index"
});
}]);
And this is my Navbar
<li>
Hem
</li>
<li ng-class="{ activeLink: isActive('/log')}" data-ng-hide="!isLoggedIn">
Logg
</li>
<li ng-class="{ activeLink: isActive('/help')}" data-ng-hide="!isLoggedIn">
Hjälp
</li>
<li ng-class="{ activeLink: isActive('/logout')}" data-ng-hide="!isLoggedIn">
Logga ut
</li>
<li ng-class="{ activeLink: isActive('/user')}" data-ng-hide="!isLoggedIn">
{{userName}}
</li>
And my problem is that when i click the {{userName}} link i am taken to the index page.
And this error only occurs on the live server when the js is minified, if it is unminified on the server so does it work like intended.
If i run this site localy i can use both the regular version and the minified one and the routing behaves like intended.
The console does not show any errors when i click on the link and whn i inspect the html in chrome so does it have the correct html
Johan Karlsson.
I have tried pointing the {{userName}} link to "#/log" and it worked fine.
Here is my user controller
(function () {
var app = angular.module("connectPortal");
var userController = ['$scope', 'authService', function ($scope, authService) {
authService.authenticateUser();
$scope.var = "var variable from HelpController";
}];
app.controller("UserController", userController);
}());
And this is my log controller
(function () {
var app = angular.module("connectPortal");
var logController = ['$scope', 'authService', function ($scope, authService) {
authService.authenticateUser();
$scope.var = "var variable from LogController";
}];
app.controller("LogController", logController);
}());

AngularJs $routeProvider is not working with MVC

When I am using $routeProvider with MVC.Net its not working.
I am using Write up Backend example for MVC.Net.
Following is the route I am using
config(function($routeProvider) {
$routeProvider.
when('/', { controller: ListCtrl, templateUrl: 'home/listitem' }).
when('/home', { controller: ListCtrl, templateUrl: 'home/listitem' }).
when('/edit/:projectId', { controller: EditCtrl, templateUrl: '/home/detail' }).
when('/new', { controller: CreateCtrl, templateUrl: '/home/detail' }).
otherwise({redirectTo:'/'});
});
but unfortunately it is not calling listitem or details.
This works fine. Setup your RouteConfig.cs as follows:
// Will handle partial page view requests
routes.MapRoute(
name: "Partials",
url: "partials/{controller}",
defaults: new { controller="Home", action = "Index" }
);
// Will handle all other requests by sending it to the main controller
routes.MapRoute(
name: "Application",
url: "{*url}",
defaults: new { controller = "Main", action = "Index" }
);
Then your angular config for routing like this:
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: '/partials/home',
controller: 'HomeController'
})
.when('/home', {
templateUrl: '/partials/home',
controller: 'HomeController'
})
.when('/gallery', {
templateUrl: '/partials/gallery',
controller: 'GalleryController'
});
.when('/services', {
templateUrl: '/Services',
controller: 'ServicesController'
});
// NOTE: This part is very important
$locationProvider.html5Mode(true);
}
]);
And your MVC controllers:
public class MainController : Controller
{
public ActionResult Index()
{
return View();
}
}
public class HomeController : Controller
{
public ActionResult Index()
{
return PartialView("_Home");
}
}
public class GalleryController : Controller
{
public ActionResult Index()
{
return PartialView("_Gallery");
}
}
Put your partial views in the shared folder.
Now, behind the scenes you can do everything like you normally would with an MVC controller and view, including razor and all that.
I have also this problem before I try this solution in config file.
config file
myapp.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
// Specify the three simple routes ('/', '/About', and '/Contact')
$routeProvider.when('/', {
templateUrl: '/Home/Home',
controller: 'homeCtrl',
});
$routeProvider.when('/Login', {
templateUrl: '/account/Index',
controller: 'loginCtrl',
});
$routeProvider.when('/About', {
templateUrl: '/Home/About',
controller: 'aboutCtrl',
});
$routeProvider.when('/Contact', {
templateUrl: '/Home/Contact',
controller: 'contactCtrl'
});
$routeProvider.when('/First', {
templateUrl: '/account/First',
controller: 'firstCtrl'
});
$routeProvider.when('/Fullpage', {
templateUrl: '/Home/Fullpage',
controller: 'fullpageCtrl'
});
$routeProvider.otherwise({
redirectTo: '/'
});
// Specify HTML5 mode (using the History APIs) or HashBang syntax.
//$locationProvider.html5Mode({ enabled: true, requireBase: false });
$locationProvider.html5Mode(false);}]);
index.cshtml file
<a class="brand" href="#/">Simple Routing</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
<li>Login</li>
<li>first</li>
<li>fullpage</li>
</ul>
</div><!--/.nav-collapse -->
As #jpmorin suggested, unless for some reason you need to dynamically generate views in a way that AngularJS can't do, the MVC views are superfluous. You just need static files to serve, and some data-binding for them. Look at BreezeJS as a solution to that.
If this doesn't satisfy you, you would need to present your MVC code for a better answer. I personally suggest the former solution.

Categories

Resources