Routing does not work in angularjs - javascript

I am very new to angular js.
I have implemented routing in angular js but it does not redirect me to the pages I have stated in the route.js
here is the code:
Route.js
var sampleApp = angular.module('sampleApp', []);
sampleApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/getplaces', {
templateUrl: 'getplaces.html',
controller: 'ListCtrl',
}).
when('/getuncategorisedplaces', {
templateUrl: 'list.html',
controller: 'uncatCtrl'
})
.otherwise ({
redirectTo: '/getplaces'
});
}]);
Controller.js
function uncatCtrl($scope, $http) {
$http.get('http://94.125.132.253:8000/getuncategorisedplaces').success(function (data) {
$scope.places = data;
console.log(data);
}
)}
// get places
function ListCtrl($scope, $http) {
$http.get('http://94.125.132.253:8000/getplaces').success(function (data) {
$scope.places = data;
console.log("Successful")
console.log(data);
}
)}
HTML code includes ng view and href such as href="#getplaces"
<body ng-app="sampleApp" >
<div class="container">
<div class="row">
<div class="col-md-3">
<ul class="nav">
<li> <a class= "linha" href="#getplaces"> Get places </a></li>
<li><a class= "linha" href="post.html"> Post a movie </a></li>
<li><a class= "linha" href="#getuncategorisedplaces">List of uncategorised places </a></li>
</ul>
</div>
<div class="col-md-9">
<div ng-view></div>
</div>
</div>

Check that you have both scripts included (angular and ngroute)
<script src='angular.js'>
<script src='angular-route.js'>
Then check that you are including that module in your app:
var sampleApp = angular.module('sampleApp', ['ngRoute']);
As of Angular 1.2.0, angular-route is a separate module
refer to the angular documentation:
https://docs.angularjs.org/api/ngRoute

Here is an example code that i have written a while ago.
var app = angular.module('test', ['ngRoute','ngGrid','ngBootstrap', 'http-auth-interceptor','ui.bootstrap','ngCookies','ngSanitize']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/sign-in', {templateUrl: 'partials/login/signin.html', controller: LoginCtrl}).
when('/admin/sign-in', {templateUrl: 'partials/login/userManagementSignin.html', controller: LoginCtrl}).
otherwise({redirectTo: '/dashboard'});
}]);

Related

Views are not loading with ngRoute

Hi I am having an issue with my code here where I can't seem to get my views to load within my template.
Here are my tags:
<script language="JavaScript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular-route.js"></script>
Here is my JS:
angular.module('dnsApp', ["ngRoute"])
var app = angular.module('dnsApp');
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/reporting.html'
})
.when('/reporting', {
templateUrl: 'views/reporting.html'
})
.when('/detectionSummary', {
templateUrl: 'views/detection-summary.html'
})
.when('/operationalMetrics', {
templateUrl: 'views/operational-metrics.html'
});
}]);
Here is my HTML:
<ul class="nav navbar-nav">
<li class="active"><i class="fa fa-dashboard"></i> <span class="sr-only">(current)</span></li>
<li><i class="fa fa-bolt"></i></li>
<li><i class="fa fa-bar-chart"></i></li>
</ul>
Nothing shows up and I am relatively new to AngularJs so any help would be much appreciated. Thanks!
You should not declare the module again, change it as
//remove this line angular.module('dnsApp', ["ngRoute"])
var app = angular.module('dnsApp', ["ngRoute"])
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/reporting.html'
})
.when('/reporting', {
templateUrl: 'views/reporting.html'
})
.when('/detectionSummary', {
templateUrl: 'views/detection-summary.html'
})
.when('/operationalMetrics', {
templateUrl: 'views/operational-metrics.html'
});
}]);
you should add your module js to your tags in your "index".
also a ng-view in your main index.
documentation:https://docs.angularjs.org/api/ngRoute/directive/ngView

How to show one div on click and hide others on click using ui-route?

my js:
var app = angular.module("dashboardApp", ["ngMaterial", "ngAnimate", "ngSanitize", "ui.bootstrap", "ngAria", "ui.router", "datatables", "gridshore.c3js.chart"]);
app.config(function($stateProvider, $urlRouterProvider, $locationProvider){
$locationProvider.hashPrefix('');
$urlRouterProvider.otherwise('/systems');
$stateProvider
.state('systems',{
url:"/systems",
templateUrl: 'pages/systems.html'
})
.state('summary', {
url:"/summary",
controller:"maxeCtrl",
templateUrl: 'pages/summary.html'
});
});
app.run(function($rootScope, $location, $anchorScroll, $stateParams, $timeout) {
$rootScope.$on('$stateChangeSuccess', function(newRoute, oldRoute) {
$timeout(function() {
$location.hash($stateParams.scrollTo);
$anchorScroll();
}, 100);
});
});
Here i am trying to inject $anchorScroll and it will scroll you to any element with the id found in $location.hash() ----> which in case here is incident.
page1:
<div class="system_row2">
<div class="col-sm-3">Today Incident's:</div>
<div class="col-sm-9 ">
<div class="col-sm-12">
<a ui-sref="summary({scrollTo:'incident'})">
</a>
</div>
Page2: i am using accordion here and providing id="incident" which will scroll to this element.
<div id="abc">
this is div 1
</div>
<div uib-accordion-group id="incident" class="panel-default">
<uib-accordion-heading>
<div class="accordion_heading">Incidents</div>
</uib-accordion-heading>
<uib-accordion-body> </uib-accordion-body>
<table>
</table>
</div>
Mycontroller:
app.controller("maxeCtrl", ["$scope", "MAXeService", "DTOptionsBuilder", "$timeout", function($scope, MAXeService, DTOptionsBuilder, $timeout) {
console.log("Angular: MAXeCtrl in action")
$scope.oneAtATime = true;
$scope.status = {
isFirstOpen: true,
isSecondOpen: true
};
I want div id="incident" to be displayed when user clicks on "summary({scrollTo:'incident'})" and the other div with id="abc" should hide.
Appreciate any kind of help in advance.
I think you are looking for named views. Check here
https://github.com/angular-ui/ui-router/wiki/Multiple-Named-Views
Sample from above link
<!-- index.html -->
<body>
<div ui-view="filters"></div>
<div ui-view="tabledata"></div>
<div ui-view="graph"></div>
</body>
Routing
$stateProvider
.state('report',{
views: {
'filters': {
templateUrl: 'report-filters.html',
controller: function($scope){ ... controller stuff just for filters view ... }
},
'tabledata': {
templateUrl: 'report-table.html',
controller: function($scope){ ... controller stuff just for tabledata view ... }
},
'graph': {
templateUrl: 'report-graph.html',
controller: function($scope){ ... controller stuff just for graph view ... }
}
}
})
for ui-router >=1.0 check here https://ui-router.github.io/guide/views#multiple-named-uiviews

$location.path change url but no redirecting

I want to redirect to another page by clicking a button, but when I click on a button, URL is changed, but it is not redirected, I have to refresh the page with new URL. The same is also happening when I click on link.
locationController.js
angular.module('reservationModule').controller('locationController', function($scope, $location){
$scope.setLocation = function (url) {
$location.path(url);
};
})
reservationModule.js
(function () {
var resModule = angular.module('reservationModule', ['ngRoute']);
resModule.controller('HomeController', function ($scope) { // here $scope is used for share data between view and controller
$scope.Message = "Yahoooo! we have successfully done our first part.";
});
resModule.config(function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: '/Home/Index.cshtml',
controller: 'locationController'
})
.when('/Home/Index', {
templateUrl: '/Home/Index.cshtml',
controller: 'locationController'
})
.when('/Home/Registration', {
templateUrl: '/Home/Registration.cshtml',
controller: 'registerController'
})
.when('/Home/Login', {
templateUrl: '/Home/Login.cshtml',
controller: 'loginController'
})
.otherwise({ redirectTo: '/' });
});
})();
Index.cshtml
#{
// Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Webový rezervační systém";
}
<base href="/">
<div class="container" ng-controller="locationController">
<header class="header">
<div class="headerleft">
<div class="headerlogo">
<img alt="reservation" src="../Content/pics/vetstoria-logo.jpg" width="50" height="50">
</div>
</div>
<div class="headerright">
<p class="headerlogintext">
<a class="btn headerlogin" href="/Home/Login" style="text-decoration:none">Přihlašte se</a>
</p>
</div>
</header>
<div class="content">
<h1 class="content-title">Webový rezervační systém</h1>
<p class="content-title-text">V našem rezervačním systému se můžete rezervovat na cokoliv chcete. Ať už si chcete rezervovat sportoviště, nějaký kurz nebo jiné, u nás to jde snadno.</p>
<p class="content-title-text">Pro začátek vám stačí jediné.</p>
<button class="btn-big" ng-click="setLocation('/Home/Registration')">Registrovat</button>
</div>
<!-- <ul class="menuUl">
<li>#Html.ActionLink("Register", "Registration")</li>
</ul>-->
#section Scripts{
<script src="~/Scripts/Angular_Controllers/locationController.js"></script>
}
I read some topics about this, but I don't know, if an error is in the module, or in the controller.
I had a similar issue. The template url should point to ".html" rather than ".cshtml". When you try to access files inside the Default Folders created by Visual Studio, for some reason you cannot access it. So try changing your path.

jQuery Nav's anchor click not working with AngularJS

I have a Home.html screen and its corresponding Angularjs controller(HomeController.js). I am using jQuery Navigation sidebar on home screen. This navigation sidebar has a logout list item (li). I have given ng-click="logout()" to this li (list item), and I have defined logout() in HomeController.js.
When I click on logout, It doesn't give alert, probably it's not going to this controller.
Home.html
<nav id="menu">
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12 sidebar-nav-menu">
<div class="menu_nav">
<ul>
<li>
<a href="#" ng-click="logout();">
<img src="img/left-pannel/logout#2x.png" id="nav-icn-home" alt="" class="sidebar-menu-icons">
<span class="nav-menu-text">Logout</span>
</a>
</li>
</ul>
</div>
</div>
</div></nav>
HomeController.js
app.controller("HomeController", function ($scope, $location, $window, $compile) {
$scope.logout = function(){
alert("Click");
$location.path("/Login");
}});
config.js
var tkitApp = angular.module('tkit', ['ngRoute']);tkitApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/LaunchScreen.html',
controller: 'LaunchScreenController'
}).when('/Login', {
templateUrl: 'views/Login.html',
controller: 'LoginScreenController'
}).when('/Home', {
templateUrl: 'views/Home.html',
controller: 'HomeController'
}).otherwise({ redirectTo: '/' });}]);
I am not even getting alert on click of logout list item.
Logcat when Home.html gets loaded
03-11 17:34:37.530: I/chromium(29156): [INFO:CONSOLE(2)] "HomeController loaded", source: file:///android_asset/www/js/controller/HomeScreenController.js (2)
Your controller name is different in routing
$routeProvider.when('/', {
templateUrl: 'views/LaunchScreen.html',
controller: 'LaunchScreenController'
}).when('/Login', {
templateUrl: 'views/Login.html',
controller: 'LoginScreenController'
}).when('/Home', {
templateUrl: 'views/Home.html',
controller: 'HomeController'
}).otherwise({ redirectTo: '/' });}]);
And Controller is
app.controller("HomeController", function ($scope, $location, $window, $compile) {
$scope.logout = function(){
alert("Click");
$location.path("/Login");
}});
Please change your controller name like this
app.controller("HomeScreenController", function ($scope, $location, $window, $compile) {
$scope.logout = function(){
alert("Click");
$location.path("/Login");
}});
It will work

How to make Angular Routing with title instead of id?

I am building a blog with angular and am currently working on the routes. I have the routes working with routeParams but angular gives it a random number and the url ends like http://localhost/kensproblems/#/posts/2
I want it to either automatically grab the title and use it as the parameter on the URL or use the property called id on the json file such as http://localhost/kensproblems/#/posts/title-of-post
Is this possible with $routeParams?
app.js
angular.module('app', [
'ngRoute',
'app.controllers',
'ui.router',
'ngSanitize'
])
.config(['$routeProvider', '$urlRouterProvider', function($routeProvider, $urlRouterProvider){
$routeProvider
.when('/posts', {
templateUrl: 'views/posts.html',
controller: 'PostListController'
})
.when('/posts/:id', {
templateUrl: 'views/singlepost.html',
controller: 'PostDetailController'
})
.otherwise({
redirectTo: '/'
});
}]);
controllers.js
angular.module('app.controllers', ['app.directives'])
/* Controls the Blog */
.controller('PostListController', ['$scope', '$http', function($scope, $http){
$http.get('data/posts.json').success(function(response){
$scope.posts = response;
});
}])
.controller('PostDetailController', ['$scope', '$http', '$routeParams', '$sce', function($scope, $http, $routeParams, $sce){
$http.get('data/posts.json').success(function(response){
$scope.post = response[$routeParams.id];
console.log($routeParams.id);
console.log($scope.post.id);
});
}])
posts.html
<div class="container" id="postList">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div ng-repeat="post in posts | orderBy:post.date" class="post">
<h2 class="blog-title">{{post.title}}</h2>
<span class="date">Posted on {{post.date | date:'MMM dd, yyyy'}}</span>
<div class="row top10">
<div class="col-md-8">
<div class="post-content">{{post.headline}}</div>
<a class="read-more" href="#/posts/{{posts.indexOf(post)}}">Read more</a>
</div>
</div>
</div>
</div>
</div>
</div>
singlepost.html
<div class="container" id="singlePost">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<h1>{{post.id}}</h1>
<h1>{{post.title}}</h1>
<span class="date">Posted on {{post.date | date:'MMM dd, yyyy'}}</span>
<h3>{{post.headline}}</h3>
<div class="postContent" ng-bind-html="post.content"></div>
</div>
</div>
</div>
You will need to change two main things, first how the URLs are generated, and second how the post is recovered.
Generate URL from title
Not any title will be valid as URL, so you need to use slugs.
In the view:
<a class="read-more" href="#/posts/{{getSlug(post.title)}}">Read more</a>
In the controller:
$scope.getSlug = function(text){
return text.replace(/\W+/g, '-');
};
Search post from slug
Currently, you are just fetching the post from the array as an index, which is conceptually wrong (you will notice this after remove one post). Instead, make a search through the array. This will be really simple if you use lodash.
Something like this would work:
$scope.post = _.find(response, function(post) {
return post.title.replace(/\W+/g, '-') === $routeParams.id;
});
Stack Overflow won't let me comment yet so I'll post here. I looks like your passing the index of the post in the array instead of one of the properties. Look at changing:
href="#/posts/{{posts.indexOf(post)}}"
To something like:
ng-href="#/posts/{{post.title}}"

Categories