How to properly route with angular - angularjs

I'm pretty new to angular and i'm trying to make a simple application, that switches few views with ng-view and ng-route.
for some reason, every link that i click always routes me to the same controller (HomeController).
This is my config
(function(){
'use strict';
angular
.module('app',['ngRoute'])
.config(myConfig);
myConfig.$inject = ['$routeProvider'];
function myConfig($routeProvider){
//noinspection JSUnresolvedFunction
$routeProvider
.when('/',{
templateUrl : 'templates/home.html',
controller : 'HomeController',
controllerAs : 'vm'
})
.when('/shop', {
templateUrl : 'templates/shop.html',
controller : 'ShopController',
controllerAs : 'vm'
})
.when('/cart', {
templateUrl : 'templates/cart.html',
controller : 'CartController',
controllerAs : 'vm'
})
.otherwise({
redirectTo: '/'
});
}
})();
This is my HTML:
<body ng-app="app">
<div id="site-wrapper">
<nav>
<ul>
<li class="button">Home</li>
<li class="button">Shop</li>
<li class="cart"><i class="fa fa-shopping-cart" aria-hidden="true"></i></li>
</ul>
</nav>
<ng-view></ng-view>
</div>
<script src="js/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-route.min.js"></script>
<script src="js/index.js"></script>
<script src="controllers/CartController.js"></script>
<script src="controllers/HomeController.js"></script>
<script src="controllers/ShopController.js"></script>
</body>
And here are 2 controllers for example:
(function(){
'use strict';
angular
.module('app')
.controller('CartController', CartController);
CartController.$inject = ['$scope', '$log'];
function CartController($scope, $log){
var vm = this;
$log.info('Cart CTRL loaded');
}
})();
(function(){
'use strict';
angular
.module('app')
.controller('HomeController', HomeController);
HomeController.$inject = ['$scope', '$log'];
function HomeController($scope , $log){
var vm = this;
$log.info('Home CTRL loaded');
}
})();

Off of a quick view, it seems to me that you need to remove the '#' in the href urls. So doing this may work better for you.
<nav>
<ul>
<li class="button">Home</li>
<li class="button">Shop</li>
<li class="cart"><i class="fa fa-shopping-cart" aria-hidden="true"></i></li>
</ul>
</nav>

Related

Data not displaying from service with dynamic parameter

not sure what I have wrong here but the data doesn't display with this code and the only error I get is an XML Reading error XML in booksincategory.html , any ideas? Thanks
**booksincategory.html **
<div class="category col" ng-repeat="book in detail">
<h3 class="title">{{book.title}}</h3>
</div>
controller
app.controller('BookCategoryController', ['$scope', 'bookcategories', '$routeParams', function($scope, bookcategories, $routeParams) {
bookcategories.getAllBooks($scope.id).then(function(response) {
$scope.detail = response.data.books[$routeParams.categoryId];
});
}]);
service
app.service('bookcategories', ['$http', function($http) {
return {
getAllBooks: function(id) {
return $http.get('http://52.41.65.211:8028/api/v1/categories/'+ id + '/books.json')
}
}
}]);
app.js
var app = angular.module('ReaderApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/categories/:categoryId', {
controller: 'BookCategoryController',
templateUrl: 'views/booksincategory.html'
})
.otherwise({
redirectTo: '/books'
});
});
index.html
<div class="main">
<div class="container">
<div ng-view></div>
</div>
</div>
<!-- Modules -->
<script src="js/app.js"></script>
<!-- Controllers -->
<script src="js/controllers/BookCategoryController.js"></script>
<!-- Services -->
<script src="js/services/bookcategories.js"></script>

AngularJS routing issue

Here, I want to print 'Nerve Center Dashboard' when route is '/' ,'Consumption Dashboard' for '/consumption' and same for every route in <p> tag. Please help
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script src="assets/jquery-1.12.4.min.js" type="text/javascript"></script>
<script src="assets/bootstrap-3.3.7/js/bootstrap-3.3.7.min.js" type="text/javascript"></script>
</head>
<body ng-app="myapp">
<p></p> /------------*text to be printed*-------------/
<ul class="nav nav-tabs">
<li onclick="dashboardTitle('Nerve Center Dashboard')" id="nerve">Nerve Center
</li>
<li onclick="dashboardTitle('Consumption Dashboard')" id="consumptionn">Consumption Analysis
</li>
<li onclick="dashboardTitle('Fulfillment Dashboard')" id="fulfillmentt">Fulfillment Analysis
</li>
<li onclick="dashboardTitle('Inventory Dashboard')" id="inventoryy">Inventory Analysis
</li>
</ul>
<div class='col-xs-12 rmpm' style='height:auto;'>
<div ng-view></div>
</div>
<script>
var myApp = angular.module('myApp', ['ngRoute']);
//routing for tabs
myApp.config(['$routeProvider',
function($routeProvider) {
// $locationProvider.html5Mode(true);
$routeProvider.
when('/', {
templateUrl: 'nervecenter.html',
controller: 'nervecenterController'
}).
when('/fulfillment', {
templateUrl: 'fulfillment.html',
controller: 'fulfillmentController'
}).
when('/consumption', {
templateUrl: 'consumption.html',
controller: 'consumptionController'
}).
when('/inventory', {
templateUrl: 'inventory.html',
controller: 'inventoryController'
}).otherwise({
templateUrl: 'nervecenter.html'
});
}
]);
</script>
</body>
</html>
You just have to create a global variable in angular's scope to initialize the <p> tag based on URL. Initialise the variable in each of the controllers with the desired value. You also have to create a main controller that will be in the scope of <p> tag, so that any initialization on $rootScope will reflect under this main controller.
Main Controller:
var myApp = angular.module('myApp', []);
myApp.controller('mainController', ['$scope','$rootScope' function ($scope,$rootScope) {
});
}]);
First Controller:
myApp.controller('nervecenterController', ['$scope','$rootScope' function ($scope,$rootScope) {
$rootScope.title="Nerve Center Dashboard"
});
}]);
Second Controller:
myApp.controller('consumptionController', ['$scope','$rootScope' function ($scope,$rootScope) {
$rootScope.title="Consumption Dashboard"
});
}]);
HTML:
<body ng-app="myapp" ng-controller="mainController">
<p>{{title}}</p>
Working Plunker: https://plnkr.co/edit/xmLZvHK57GpaIFsHzvvV?p=preview

how to add routing using angular-ui-router?

I am new to angularjs ,i make a sample app with custom directives now i add routing as well but it doesn't working.When i start project nothing is displayed in browser.
here is my index.html:
<html ng-app="myApp">
<head>
<title>Reddit New World News (Task)</title>
<link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
<script src="angular/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="myApp.js"></script>
<script src="myAppCtrl.js"></script>
<script src="routes.js"></script>
<script src="headerDirective.js"></script>
<script src="searchDirective.js"></script>
<script src="myDataDirective.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
myAppCtrl:
// TODO: Wrap in anonymous function
(function () {
var myApp = angular.module('myApp', ['ui.router']);
// TODO: min-safe with bracket notation
myApp.controller('myAppCtrl', ['$scope', '$http', function($scope, $http) {
$scope.sortType = '';
$scope.sortReverse = true;
// TODO: Keep lines short - it's easier to read
$http.get("https://www.reddit.com/r/worldnews/new.json")
.success(function (response) {
$scope.stories = response.data.children;
});
}]);
myApp.controller('aboutController',function(){
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
myApp.controller('contactController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
})();
headerDirective.html:
<div class="top-header"></div>
<div class="container">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="header">
<h1>Reddit</h1>
</div>
<div class="header-right">
<h2>World's Latest News</h2>
</div>
<div>
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</div>
</nav>
<div class="clearfix"></div>
</div>
routes.js:
angular.module('myAppCtrl')
.config(['$stateProvider', '$locationProvider', '$urlRouterProvider',
function ($stateProvider, $locationProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/index.html');
// See route.webapp.js for allowed routes
$stateProvider
.state('app', {
templateUrl: '/templates/app.html',
controller: 'myAppCtrl',
abstract: true
})
.state('app.home', {
url: '/home',
templateUrl: '/templates/index.html',
controller: 'myAppCtrl'
})
.state('app.about', {
url: '/about',
templateUrl: '/templates/about.html',
controller: 'aboutController'
})
.state('app.contact', {
url: '/contact',
templateUrl: '/templates/contact.html',
controller: 'contcatController'
});
$locationProvider.html5Mode(true);
}
]);
})();
any guide thanks.
First there is a problem with your config block :
myApp.config(...)
not
angular.module('myAppCtrl').config(...);
Else you're redeclaring a new module. That doesn't make sense. You mix up controllers and module, that's two different things.
Then you have to change some things in your HTML file :
If you're using UI-Router it's :
<div ui-view></div>
not like ngRouter :
<div ng-view></div>
Then you're using $locationProvider.html5Mode(true);
So you have to configure your server to emulate paging, see doc.
Finally you have to add the base href of your angular application in the <head> tag like that :
<base href="/">

Angular - main view not loading when page loads

I'm new to Angular and I'm trying to build a personal site using routes to change the views.
I've been able to get the nav to change class to active depending on what's clicked, but now the problem I'm having is that the main view doesn't load when the page loads (everything works on click though).
If anyone can help, I'd really appreciate it. If I've made any dumb errors, please let me know.
Also, I've got the view outside the controller div, should it be inside?
Thanks
HTML:
'use strict';
angular.module('myApp', [
'ngAnimate',
'ngAria',
'ngCookies',
'ngMessages',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
var myApp = angular.module('myApp', []);
myApp.config(function($routeProvider) {
$routeProvider
.when('/main', {templateUrl:'views/main.html', controller:'WidgetsController'})
.when('/about', {templateUrl:'views/about.html', controller:'WidgetsController'})
.otherwise({
redirectTo: '/'
});
});
myApp.controller('WidgetsController', function($scope) {});
myApp.controller('MyCtrl', function($scope, $location) {
$scope.isActive = function(route) {
return route === $location.path();
}
});
<body ng-app="myApp" class="ng-scope">
<div ng-controller="MyCtrl" class="ng-scope">
<ul class="nav nav-pills pull-right">
<li ng-class="{active:isActive('/main')}">Main</li>
<li ng-class="{active:isActive('/about')}">About</li>
</ul> </div> </div> </div>
<div ng-view=""></div>
Please see below working example
you've got twice definition for myApp make sure as well that you've all reference to all angular modules in your 'home page'
'use strict';
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider) {
$routeProvider
.when('/main', {
templateUrl: 'views/main.html',
controller: 'WidgetsController'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'WidgetsController'
})
.otherwise({
redirectTo: '/main'
});
});
myApp.controller('WidgetsController', function($scope) {});
myApp.controller('MyCtrl', function($scope, $location) {
$scope.isActive = function(route) {
return route === $location.path();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.3/angular-route.min.js"></script>
<body ng-app="myApp" class="ng-scope">
<div ng-controller="MyCtrl" class="ng-scope">
<ul class="nav nav-pills pull-right">
<li ng-class="{active:isActive('/main')}">Main
</li>
<li ng-class="{active:isActive('/about')}">About
</li>
</ul>
</div>
<div ng-view=""></div>
<script type="text/ng-template" id="views/main.html">
<h1>Main View</h1>
</script>
<script type="text/ng-template" id="views/about.html">
<h1>About View</h1>
</script>

Angular 1.2.22 routing issue with ng-view

I am new to Angular. div ng-view never works for me. Here is my code, this is copied and pasted from on of online demos. Thanks for help.
<!DOCTYPE html>
<html ng-app="sampleApp">
<head>
<title></title>
<script src="Scripts/angular-1.2.22/angular.js"></script>
<script src="Scripts/angular-1.2.22/angular-route.js"></script>
<script src="Scripts/AngularController.js"></script>
</head>
<body >
<div class="container">
<div class="row">
<div class="col-md-3">
<ul class="nav">
<li> Add New Order </li>
<li> Show Order </li>
</ul>
</div>
<div class="col-md-9">
<div ng-view></div>
</div>
</div>
</div>
</body>
</html>
---Script AngularController.js----
'use strict';
var sampleApp = angular.module('sampleApp', ['ngRoute']);
sampleApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/addOrder', {
templateUrl: 'templates/routeOne.html',
controller: 'AddOrderController'
}).
when('/showOrders', {
templateUrl: 'templates/routeTwo.html',
controller: 'ShowOrdersController'
}).
otherwise({
redirectTo: '/routeThree.html'
});
}]);
//--- Add Order Controller ----
sampleApp.controller('AddOrderController', function ($scope) {
});
//--- Show Orders Controller ----
sampleApp.controller('ShowOrdersController', function ($scope) {
});
There are 2 issues regarding your code. The first and most important is that your links are incorrect, they are missing a slash.
<li> Add New Order </li>
<li> Show Order </li>
The second issue you are currently having is that on your route definition your otherwise is trying yo redirect to a file, where it actually should try to redirect to an angular defined route. An example of this could be something like this:
$routeProvider
.when('/', {
templateUrl: 'templates/routeThree.html'
})
.when('/addOrder', {
templateUrl: 'templates/routeOne.html',
controller: 'AddOrderController'
})
.when('/showOrders', {
templateUrl: 'templates/routeTwo.html',
controller: 'ShowOrdersController'
})
.otherwise({
redirectTo: '/'
});
Cheers!

Resources