Active Class Based On Selected Menu - angularjs

I'm learning angular and try to create a navbar menu and set 'active' class based on current page.
index.html
<html lang="en" data-ng-app="Afe" class="no-js">
<head>
<!-- code omitted.. -->
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav" data-ng-init="activeMenu='AfeCoverPage'">
<li data-ng-class="{active: activeMenu=='AfeCoverPage'}" data-ng-click="activeMenu='AfeCoverPage'">AFE Cover Page</li>
<li data-ng-class="{active: activeMenu=='AfeCostEstimate'}" data-ng-click="activeMenu='AfeCostEstimate'">AFE Cost Estimate</li>
<li data-ng-class="{active: activeMenu=='AfeVariance'}" data-ng-click="activeMenu='AfeVariance'">AFE Variance</li>
</ul>
</div>
</div>
</nav>
<div data-ng-view=""></div>
<!-- code omitted.. -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</body>
</html>
app.js
angular.module('Afe', ['ngRoute', 'Afe.controllers']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/AfeCoverPage', { templateUrl: 'partials/AfeCoverPage.html', controller: 'AfeCoverPageCtrl' });
$routeProvider.when('/AfeCostEstimate', { templateUrl: 'partials/AfeCostEstimate.html', controller: 'AfeCostEstimateCtrl' });
$routeProvider.when('/AfeVariance', { templateUrl: 'partials/AfeVariance.html', controller: 'AfeVarianceCtrl' });
$routeProvider.otherwise({ redirectTo: '/AfeCoverPage' });
}]);
controllers.js
angular.module('Afe.controllers', []).
controller('GlobalCtrl', ['$scope', function ($scope) {
}]).
controller('AfeCoverPageCtrl', ['$scope', function ($scope) {
}]).
controller('AfeCostEstimateCtrl', ['$scope', function ($scope) {
}]).
controller('AfeVarianceCtrl', ['$scope', function ($scope) {
}]);
Currently it's working, when Afe Cover Page menu is clicked, the <li> element will have 'active' class, but I'm not sure whether using ng-click is the right way. The code seems to be duplicated. Could anyone show me the best way to do it?

You could just use the $location service and a function in your ng-class directive that returns a bool if it matches the current path.
<div class="collapse navbar-collapse" ng-controller="MenuController">
<ul class="nav navbar-nav">
<li data-ng-class="{active: isActive('/AfeCoverPage')}">AFE Cover Page</li>
<li data-ng-class="{active: isActive('/AfeCostEstimate')}">AFE Cost Estimate</li>
<li data-ng-class="{active: isActive('/AfeVariance')}">AFE Variance</li>
</ul>
</div>
With a controller:
.controller('MenuController', function ($scope, $location) {
$scope.isActive = function (path) {
return $location.path() === path;
}
});

Related

AngularJS controller not properly loaded during ng-Route otherwise()

I'm learning an example of a single page application using angularjs. Here's the relevant code:
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"/>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
<script>
var app = angular.module('app', ['ngRoute']);
app.config(function ($routeProvider) {
// configure the routes
$routeProvider
.when('/', {
// route for the home page
templateUrl: 'pages/home.html',
controller: 'homeController'
})
.when('/about/', {
// route for the about page
templateUrl: 'pages/about.html',
controller: 'aboutController'
})
.when('/contact/', {
// route for the contact page
templateUrl: 'pages/contact.html',
controller: 'contactController'
})
.otherwise({
// when all else fails
templateUrl: 'pages/routeNotFound.html',
controller: 'notFoundController'
});
});
app.controller('homeController', function ($scope) {
$scope.message = 'Welcome to my home page!';
});
app.controller('aboutController', function ($scope) {
$scope.message = 'Find out more about me.';
});
app.controller('contactController', function ($scope) {
$scope.message = 'Contact us!';
});
app.controller('notFoundController', function ($scope) {
$scope.message = 'There seems to be a problem finding the page you wanted';
$scope.attemptedPath = $location.path();
});
</script>
</head>
<body ng-controller="homeController">
<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">My Website</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><i class="fa fa-home"></i> Home</li>
<li><i class="fa fa-shield"></i> About</li>
<li><i class="fa fa-comment"></i> Contact</li>
</ul>
</div>
</nav>
</header>
<div id="main">
<!-- this is where content will be injected -->
<div ng-view></div>
</div>
</body>
</html>
routeNotFound.html
<div class="jumbotron text-center">
<h1>This is not good</h1>
<p>{{message}}</p>
<p class="has-error">{{attemptedPath}}</p>
</div>
When I click on Home or About or Contact the page renders correctly. But if I visit any other URL, routeNotFound.html is injected correctly to div[ng-view] but the data is not bound. I get:
This is not good
{{message}}
{{attemptedPath}}
It seems notFoundController is not correctly made available to the view when .otherwise() is called inside route. $scope.message and $scope.attemptedPath is not bound to the view.
You are missing $locationService injection in your notFoundController
app.controller('notFoundController', function ($scope,$location /*<--- location injected here*/) {
$scope.message = 'There seems to be a problem finding the page you wanted';
$scope.attemptedPath = $location.path();
});
Here is a full sample:
var app = angular.module('app', ['ngRoute']);
app.config(function ($routeProvider) {
// configure the routes
$routeProvider
.when('/', {
// route for the home page
template: '<h1>My page home</h1><br />{{message}}',
controller: 'homeController'
})
.when('/about/', {
// route for the about page
template: '<h1>My page about</h1><br />{{message}}',
controller: 'aboutController'
})
.when('/contact/', {
// route for the contact page
template: '<h1>My page contact</h1><br />{{message}}',
controller: 'contactController'
})
.otherwise({
// when all else fails
template: '<h1>Not found page</h1><br />{{message}}',
controller: 'notFoundController'
});
});
app.controller('homeController', function ($scope) {
$scope.message = 'Welcome to my home page!';
});
app.controller('aboutController', function ($scope) {
$scope.message = 'Find out more about me.';
});
app.controller('contactController', function ($scope) {
$scope.message = 'Contact us!';
});
app.controller('notFoundController', function ($scope,$location) {
$scope.message = 'There seems to be a problem finding the page you wanted';
$scope.attemptedPath = $location.path();
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"/>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
<script>
</script>
</head>
<body ng-controller="homeController">
<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">My Website</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><i class="fa fa-home"></i> Home</li>
<li><i class="fa fa-shield"></i> About</li>
<li><i class="fa fa-comment"></i> Contact</li>
<li><i class="fa fa-comment"></i> Not found</li>
</ul>
</div>
</nav>
</header>
<div id="main">
<!-- this is where content will be injected -->
<div ng-view></div>
</div>
</body>
</html>

AngularJS routing: Views are not getting updated

I am learning how to implement routing in AngularJS. Everything else is working fine but the views are not getting updated when I click on the navigation.
How can I achieve the desired functionality in the application? I want the navigation to take us to the desired pages without refreshing the page and that's quite obvious.
Here is the code.
Index.html
<!DOCTYPE html>
<html ng-app="routingApp">
<head>
<title>AngularJS routing</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.7/angular-route.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="routingAppController">
<!-- Header and Navigation -->
<header>
<nav class= "navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">Angular Routing App</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</nav>
</header>
<!-- Main Body where content will be injected -->
<div id="main">
<div ng-view></div>
</div>
</body>
</html>
Script.js
(function(){
'use strict';
var app = angular.module('routingApp', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl : 'pages/home.html',
controller : 'routingAppController'
})
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'aboutController'
})
.when('/contact', {
templateUrl : 'pages/contact.html',
controller : 'contactController'
});
});
app.controller('routingAppController', function($scope){
$scope.message = "This will get updated for sure!";
});
app.controller('aboutController', function($scope){
$scope.message = "This is the about page and it looks awesome!";
});
app.controller('contactController', function($scope){
$scope.message = "This is the contact page!";
});
})();
One of the pages
<div class="jumbotron text-center">
<h1>Home Page</h1>
<p>{{ message }}</p>
</div>

AngularJS: single page app demo not working

i'm having this online course on AngularJS, which provides the code in folders, according to the lesson. This one is about routing and single page applications; similar demos and structures work on plunker (like this one ) but not in my machine...I don't understand why, can someone help me out?
EDIT: actually, if I download this demo the thing wont work...
INDEX file:
<html lang="en-us" ng-app="myApp">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta charset="UTF-8">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<style>
html, body, input, select, textarea
{
font-size: 1.05em;
}
</style>
<script src="//code.angularjs.org/1.3.0-rc.1/angular.min.js"></script>
<script src="//code.angularjs.org/1.3.0-rc.1/angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">AngularJS</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><i class="fa fa-home"></i> Home</li>
<li><i></i> Second</li>
</ul>
</div>
</nav>
</header>
<div class="container">
<div ng-view></div>
</div>
</body>
</html>
The Module file: APP.JS
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/main.html',
controller: 'mainController'
})
.when('/second', {
templateUrl: 'pages/second.html',
controller: 'secondController'
})
.when('/second/:num', {
templateUrl: 'pages/second.html',
controller: 'secondController'
})
});
myApp.controller('mainController', ['$scope', '$log', function($scope, $log) {
$scope.name = 'Main';
}]);
myApp.controller('secondController', ['$scope', '$log', '$routeParams', function($scope, $log, $routeParams) {
$scope.num = $routeParams.num || 1;
}]);
Pages one and two (views):
<h1>This is Main.</h1>
<h3>Scope value: {{ name }}</h3>
<h1>This is second.</h1>
<h3>Scope route value (on second page): {{ num }}</h3>
The folder structure. The code is as suggested
Your references for angular and bootstrap are not correct
Angularjs
<script src="https://code.angularjs.org/1.3.0-rc.1/angular.min.js"></script>
<script src="https://code.angularjs.org/1.3.0-rc.1/angular-route.min.js"></script>
Bootstrap
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
You need to correct you urls like this
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/main.html',
controller: 'mainController'
})
.when('/second', {
templateUrl: 'pages/second.html',
controller: 'secondController'
})
.when('/second/:num', {
templateUrl: 'pages/second.html',
controller: 'secondController'
})
});
myApp.controller('mainController', ['$scope', '$log', function($scope, $log) {
$scope.name = 'Main';
}]);
myApp.controller('secondController', ['$scope', '$log', '$routeParams', function($scope, $log, $routeParams) {
$scope.num = $routeParams.num || 1;
}]);
<html lang="en-us" ng-app="myApp">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta charset="UTF-8">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<style>
html, body, input, select, textarea
{
font-size: 1.05em;
}
</style>
<script src="https://code.angularjs.org/1.3.0-rc.1/angular.min.js"></script>
<script src="https://code.angularjs.org/1.3.0-rc.1/angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">AngularJS</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><i class="fa fa-home"></i> Home</li>
<li><i></i> Second</li>
</ul>
</div>
</nav>
</header>
<div class="container">
<div ng-view></div>
</div>
</body>
</html>
Also you need to add a page for the view on the following path in project pages/main.html
You need to use your application throught the localhost like this:
Just mount your project on HTTP server.
$> sudo npm -g live-server
$> cd path/to/root/dir/project
$> live-server
EDIT: and eventually, include every time your scripts at bottom of body:
<body>
.....
.....
.....
<script src="//code.angularjs.org/1.3.0-rc.1/angular.min.js"></script>
<script src="//code.angularjs.org/1.3.0-rc.1/angular-route.min.js"></script>
<script src="app.js"></script>
</body>

ngRoute not working as expected

I am trying to learn about routes in in angular and I am having some trouble getting the proper text to display. It seems that everything is working without errors when I run my page however, the view is not changing from main.html to second.html when I click on the link.
Here are some snips of my code...
<html ng-app="myApp">
<!-- load angular via CDN -->
<script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
<script src="https://code.angularjs.org/1.6.1/angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" >AngularJS</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><i class="fa fa-home"></i> Home</li>
<li><i></i>Second</li>
</ul>
</div>
</nav>
</header>
<div class="container">
<div ng-view></div>
</div>
</body>
main html contents:
<h1>This is main</h1>
second html contents:
<h1>This is second</h1>
app.js
var myApp = angular.module('myApp', ["ngRoute"]);
myApp.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "pages/main.html",
controller: "mainController"
})
.when("/second", {
templateUrl: "pages/second.html",
controller: "secondController"
})
});
myApp.controller('mainController', ["$scope", "$log", "$location", function($scope, $log, $location) {
}]);
myApp.controller('secondController', ["$scope", "$log", "$location", function($scope, $log, $location) {
}]);
try ui-router instead of ngRoute
I am using it in a lot of projects and its working very good
doc: https://github.com/angular-ui/ui-router
At first line in your index.html, you're opening a <html> tag, but you're closing with a </head> one, plus, I'd recommand placing your ng-app="myApp" in the opening <body> tag, this way :
<head>
<!-- everything you need -->
</head>
<body ng-app="myApp">
<!-- and stuff -->
</body>
If this doesn't change anything after correcting these errors, I really don't know what's the problem, everything looks ok.

AngularJS How to add template inside of a HTML div

I have a index page which is divided to 4 divs. What i m trying to do is when the user clicks on a link in the navigation bar, the template is loaded in the div. For example, if the user clicks on the ex1 then the first div in the html supposed to show the content of the template. Any ideas how can i do it ?
<body ng-controller="MainController">
<nav class="navbar navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div>
<ul class="nav navbar-nav">
<li ng-class="{ active: isActive('#ex1')}">Ex1</li>
<li ng-class="{ active: isActive('#ex2')}">Ex2</li>
<li ng-class="{ active: isActive('#ex3')}">Ex3</li>
<li ng-class="{ active: isActive('#ex4')}">Ex4</li>
</ul>
</div>
</div>
</nav>
<div id="div1">
</div>
<div id="div2">
</div>
<div id="div3">
</div>
<div id="div4">
</div>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade
your browser</a> to improve your experience.</p>
<![endif]-->
<div ng-view>
</div>
<footer ng-include="'partials/footer.html'" style="position: fixed; bottom: 0"></footer>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="app.js"></script>
<script src="controllers/Ex1Ctrl.js"></script>
<script src="controllers/Ex2Ctrl.js"></script>
<script src="controllers/Ex3Ctrl.js"></script>
<script src="controllers/Ex4Ctrl.js"></script>
<script src="services/ex1Service.js"></script>
<script src="components/version/version.js"></script>
<script src="components/version/version-directive.js"></script>
<script src="components/version/interpolate-filter.js"></script>
</body>
app.js
use strict';
// Declare app level module which depends on views, and components
var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/ex1', {
templateUrl: 'partials/ex1.html',
controller: 'Ex1Ctrl'
});
$routeProvider.when('/ex2', {
templateUrl: 'partials/ex2.html',
controller: 'Ex2Ctrl'
});
$routeProvider.when('/ex3', {
templateUrl: 'partials/ex3.html',
controller: 'Ex3Ctrl'
});
$routeProvider.when('/ex4', {
templateUrl: 'partials/ex4.html',
controller: 'Ex4Ctrl'
});
$routeProvider.otherwise({
redirectTo : '/'
});
}]);
app.controller('MainController', ['$scope', function ($scope) {
}]);
Ex1 template
<div id = "ex1">
<div >click to see your lucky number<button class="btn btn-default" style="margin-left: 5px" ng-click="findRandom()">Click</button></div>
<div>{{random}}</div>
</div>
Ext1 controller
angular
.module('app')
.controller('Ex1Ctrl', ['$scope','Calculator', function ($scope,Calculator) {
$scope.findRandom = function(){
$scope.random=Calculator.number();
}
}]);
Currently your template will populate the <ng-view> view tag when you navigate to '/ext1'. If I understand you correctly you want the template contents to appear inside div1 when '/ext1' is navigated to...
Off the top of my head below code would achieve that by listening for the $routeUpdate event...
app.directive('luckyNumberGenerator', function(){
return {
templateUrl: '/path/to/the/template.html',
controller: function($scope, $location){
$scope.$on('$routeUpdate', function(){
$scope.showLuckyNumberGenerator = $location.path() === '/ext1';
});
}
}
});
... add an ng-show to your template...
<div id = "ex1" ng-show="showLuckyNumberGenerator">
<div >click to see your lucky number<button class="btn btn-default" style="margin-left: 5px" ng-click="findRandom()">Click</button></div>
<div>{{random}}</div>
</div>
.. and put the directive into the div.
<div id="div1">
<lucky-number-generator></lucky-number-generator>
</div>
It's worth noting that when you want to do any complex routing of panels and nested partial views you should look into using ui.router...

Resources