I am using Angular $route for nav highlighting, but the highlighting does not show. Here is the code for the navigation...
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body ng-app="myApp">
<div ng-controller="myController" class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li ng-class="{active: $route.current.activetab == 'home'}">Home</li>
<li ng-class="{active: $route.current.activetab == 'audio'}">Audio</li>
<li ng-class="{active: $route.current.activetab == 'bio'}">Artist Bio</li>
<li ng-class="{active: $route.current.activetab == 'contact'}">Contact</li>
</ul>
</div>
</body>
</html>
Here is the code for the AngularJS controller with $route...
app.controller("myController", function($scope,$http, $route) {
$http.post('myform.php')
.then(function successCallback(response){
$scope.detail = response.data;
if($scope.detail){
console.log("success");
} else{
console.log("no data");
}
}, function errorCallback(response) {
console.log("error");
});
$scope.$route = $route;
});
Did you include the js library?
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.js"></script>
Did you inject ngRoute into your angular module?
var app = angular.module("myApp", ['ngRoute']);
Related
I am working in angularjs, of course, and following are the index.php (after logging in) and mainApp.js (main application after logging in). Here I am using session storage to check whether the current session is valid or not. Moreover, after logging in, the parent page, i.e. the one rendered by index.php is visible along with its navigational bar, but the templates are no where to be found. The google development tools show that the templates have been loaded successfully (i.e. status 200) and one can see the in the network's tab. But the templates are not rendered no matter what you select from navigational bar.
index.php
<!-- main page -->
<?php
$version = time();
?>
<!DOCTYPE html>
<html>
<head>
<!-- CSS (load bootstrap and our custon css files) -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style>
.navbar {
border-radius: 0px;
}
ul {
list-style-type: none;
}
</style>
<!-- JS (load angular, ui-router and our custom js file) -->
<script src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="js/mainApp.js"></script>
</head>
<!-- NAVIGATION -->
<body>
<div ng-app="mainApp">
<nav class="navbar navbar-inverse" role="navigation">
<div class="navbar-header">
<a class="navbar-brand"><strong>DASHBOARD</strong></a>
</div>
<ul class="nav navbar-nav navbar-left">
<li><a ui-sref="home">Home</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">Client
<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a ui-sref="addClient">Add Client</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">Service
<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a ui-sref="addService">Add Service</a></li>
</ul>
</li>
<li><a ui-sref="about">About</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a ui-sref="logout">Logout</a></li>
</ul>
</nav>
</div>
<!-- MAIN CONTENT -->
<div class="container">
<!-- THIS IS WHERE WE WILL INJECT OUR CONTENT -->
<div ui-view></div>
</div>
</body>
</html>
mainApp.js
var mainApp = angular.module('mainApp', ['ui.router']);
mainApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('home', {
url:'/',
templateUrl: function (){
if(sessionStorage.username!=="karan" || sessionStorage.password!=="123456"){
return 'templates/login.html';
}
else {
return 'templates/home.html';
}
}
})
.state('addClient', {
url:'/addClient',
templateUrl: function(){
if(sessionStorage.username!=="karan" || sessionStorage.password!=="123456"){
return 'templates/login.html';
}
else{
return 'templates/addClient.html';
}
}
})
.state('addService', {
url:'/addService',
templateUrl: function(){
if(sessionStorage.username!=="karan" || sessionStorage.password!=="123456"){
return 'templates/login.html';
}
else{
return 'templates/addService.html';
}
}
})
.state('about', {
url: '/about',
templateUrl: function (){
if(sessionStorage.username!=="karan" || sessionStorage.password!=="123456"){
return 'templates/login.html';
}
else {
return 'templates/about.html';
}
}
})
.state('logout', {
url: '/login',
templateUrl: function (){
sessionStorage.clear();
return 'templates/login.html';
}
});
});
please tell me if there's any better way instead of using sessions and also help me solve this problem. Thank you.
P.S. on a side note, i am a newbie in angularjs and would appreciate if you can guide me in how to implement login most efficiently , both performance and security wise
One way to handle this situation is adding an interceptor as follows.
mainApp.config(function ($httpProvider) {
$httpProvider.interceptors.push('loginInterceptor');
}).factory('loginInterceptor', function ($q, $window,$rootScope) {
return {
'response': function(response) {
if(sessionStorage.username!=="karan" || sessionStorage.password!=="123456"){
$rootScope.$broadcast("notLoggedIn",{statusCode : 'NOT_LOGGED_IN'});
}
else{
return response;
}
},
'responseError': function(rejection) {
return $q.reject(rejection);
}
}
})
Then handle the message 'notLoggedIn' as follows
mainApp.run(function($state,$rootScope){
$rootScope.$on("notLoggedIn",function(event,message){
$state.transitionTo('login');//Define a state with template url 'templates/login.html';
});
})
Advantage of this approach is, you will not end up checking the login status in every state definitions.
Try using ng-view instead of ui-view and see if that makes a difference, it helped in my case.
I've put this code in Html head section:
<script src="lib/smart-menus/jquery.smartmenus.min.js"></script>
<script type="text/javascript">
$(function() {
$('#main-menu').smartmenus({
subMenusSubOffsetX: 1,
subMenusSubOffsetY: -8
});
});
</script>
<link href="lib/smart-menus/sm-core-css.css" rel="stylesheet" />
<link href="lib/smart-menus/sm-blue.css" rel="stylesheet" />
and in body:
<nav id="main-nav" role="navigation">
<div id="main-menu" class="sm sm-rtl sm-blue">
<ul>
<li><a ui-sref="site.home">Home</a></li>
<li ng-repeat="menu in menus">
<a href='#'>{{menu.Title}}</a>
<ul ng-show="getHasSubMenus(menu)">
<li ng-repeat="subMenu in menu.SubMenus">
<a ui-sref="site.shopbycategory({ departmentID: subMenu.DepartmentID , categoryID: subMenu.CategoryID, searchTerm: '' })">
{{subMenu.Title}}
</a>
</li>
</ul>
</li>
<li><a ui-sref="site.contact">Contacts</a></li>
</ul>
</div>
</nav>
in the page controller I have:
function siteController($scope, $location, $rootScope, Account, $state, $stateParams, Site, $timeout) {
$timeout(function () {
$scope.getMenus(function () { // OnSuccess
$('#main-menu').smartmenus('refresh');
});
}, 1);}
Also I included jQuery 1.12 before other scripts. and I can verify that angularjs has added all the menus to the main-menu div using F12 in IE, But nothing appears in the page and I don't get any errors from these codes. Is my code correct?
I changed:
<div id="main-menu" class="sm sm-rtl sm-blue">
<ul>
to:
<ul id="main-menu" class="sm sm-rtl sm-blue">
now top level links work and submenus despite existence not showing.
I was using this example to build the login page
angular-authentication-example
Once login to this app the home screen should have multi-tab view as mentioned in the below example
plunker
<ul class="nav nav-tabs" ng-controller="TabsCtrl">
<li ng-class="tabClass(tab)" ng-repeat="tab in tabs" tab="tab">{{tab.label}}</li>
</ul>
The issue I am facing is the multi-tab is not embedded as Single page App. As mentioned in the demo it should embed in the same view but once I integrated, it is showing as different view. For example, when I click jobs it is taking to new html page but not included in the same view as in the plunker demo .I want to use the angularjs route provider instead of state provider and the reason is login authentication example is best and I don't want to change the entire logic.
Update
Version 1 (Without routing) Plunker Demo
It will redirect to a new view if you use #/jobs syntax. Here is a complete working solution without routes:
Your code on plunker is working because you didn't include ngRoute in your code.
View in plunker demo
app.js
$scope.tabs = [
{ id : 'jobs', label : 'Jobs', templateUrl:'jobs-partial.html' },
{ id : 'invoices', label : 'Invoices',templateUrl: 'invoices-partial.html' },
{ id : 'payments', label : 'Payments',templateUrl: 'payments-partial.html' }
];
$scope.activeTab = $scope.tabs[0];
$scope.changeActiveTab = function (tab) {
$scope.activeTab = tab;
};
$scope.isActiveTab = function (tabId) {
return tabId === $scope.activeTab;
}
Inside index.html
<body ng-controller="TabsCtrl">
<ul class="nav nav-tabs" >
<li ng-class="{active: isActiveTab(tab.id)}" ng-repeat="tab in tabs">
{{tab.label}}
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade" ng-class="{'in active': isActiveTab(tab.id)}" ng-repeat="tab in tabs"
ng-include="tab.templateUrl">
</div>
</div>
</body>
Version 2 (With routing) Plunker Demo
index.html
<!DOCTYPE html>
<html ng-app="plunkerApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script src="https://code.angularjs.org/1.4.8/angular-route.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
app.js
angular
.module('untitled4App', [
'ngRoute'
])
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.when('/jobs', {
templateUrl: '/views/jobs-partial.html',
controller: 'JobsCtrl'
}).when('/invoices', {
templateUrl: '/views/invoices-partial.html',
controller: 'InvoicesCtrl'
}).when('/payments', {
templateUrl: '/views/payments-partial.html',
controller: 'PaymentsCtrl'
});
// make this demo work in plunker
$locationProvider.html5Mode(false);
}])
.factory('tabsService', function () {
return {
tabs: function () {
return [
{id: 'jobs', label: 'Jobs'},
{id: 'invoices', label: 'Invoices'},
{id: 'payments', label: 'Payments'}
]
},
activeTab: '',
isActiveTab: function (tabId) {
return tabId === this.activeTab;
}
}
})
.controller('JobsCtrl', ['$scope', 'tabsService', function ($scope, tabsService) {
$scope.tabs = tabsService.tabs();
$scope.tabsService = tabsService;
tabsService.activeTab = $scope.tabs[0].id;
}])
.controller('InvoicesCtrl', ['$scope', 'tabsService', function ($scope, tabsService) {
$scope.tabs = tabsService.tabs();
$scope.tabsService = tabsService;
tabsService.activeTab = $scope.tabs[1].id;
}])
.controller('PaymentsCtrl', ['$scope', 'tabsService', function ($scope, tabsService) {
$scope.tabs = tabsService.tabs();
$scope.tabsService = tabsService;
tabsService.activeTab = $scope.tabs[2].id;
}]);
jobs.partial.html
<ul class="nav nav-tabs">
<li ng-class="{active: tabsService.isActiveTab(tab.id)}" ng-repeat="tab in tabs">
{{tab.label}}
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in active">
Jobs
</div>
</div>
invoices-partial.html
<ul class="nav nav-tabs">
<li ng-class="{active: tabsService.isActiveTab(tab.id)}" ng-repeat="tab in tabs">
{{tab.label}}
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in active">
Invoices
</div>
</div>
payments-partial.html
<ul class="nav nav-tabs">
<li ng-class="{active: tabsService.isActiveTab(tab.id)}" ng-repeat="tab in tabs">
{{tab.label}}
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in active">
Payments
</div>
</div>
I am trying to add to my Angular Js application a pagination angular JS module covered in this link (http://www.michaelbromley.co.uk/blog/108/paginate-almost-anything-in-angularjs), which is connected with How to do paging in AngularJS?.
Following the steps I have included the module's javascript file to index.html and added the module's dependency to my module's declaration. I am new to angularJS and I am sure I must be missing something basic.
The error is:
Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [ng:areq] Argument 'fn' is not a function, got string
http://errors.angularjs.org/1.2.9/ng/areq?p0=fn&p1=not%20a%20function%2C%20got%20string
at http://127.0.0.1/sessions-angularJs-...
HTML (INDEX.HTML)
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>My AngularJS App</title>
<link rel="stylesheet" href="css/app.css"/>
<link rel="stylesheet" href="css/taskman.css"/>
<script src="lib/angular/angular.js"></script>
<script src="js/app.js"></script>
<script src="lib/angular/angular-route.js"></script>
<script src="lib/angular/dirPagination.js"></script>
<script src="js/directives/loginDrc.js"></script>
<script src="js/services/loginService.js"></script>
<script src="js/controllers/priceCtrl.js"></script>
<script src="js/services/sessionService.js"></script>
<script src="js/controllers/loginCtrl.js"></script>
<script src="js/controllers/homeCtrl.js"></script>
<script src="js/controllers/campCtrl.js"></script>
<script src="js/controllers/quizCtrl.js"></script>
<script src="js/controllers/voucherCtrl.js"></script>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<div class="navbar navbar-default" id="navbar">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">Campaigning Framework</a>
</div>
<ul class="nav navbar-nav navbar-right" ng-controller="homeCtrl">
<li><i class="fa fa-home"></i> Home</li>
<li><i class="fa fa-comment"></i> Vouchers</li>
<li><i class="fa fa-shield"></i> Campaign</li>
<li><i class="fa fa-shield"></i> Quiz</li>
<li><i class="fa fa-shield"></i> Prize</li>
<li><i class="fa fa-comment"></i> Logout</li>
</ul>
</div>
</div>
<div ng-view>
</div>
<!-- In production use:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
-->
</body>
</html>
JAVASCRIPT (APP.JS)
'use strict';
// Declare app level module which depends on filters, and services
var app= angular.module('myApp', ['ngRoute'], ['angularUtils.directives.dirPagination']);
//var app= angular.module('myApp', ['ngRoute'], ['angularUtils.directives.dirPagination']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'loginCtrl'});
$routeProvider.when('/voucher', {templateUrl: 'partials/voucher.html', controller: 'voucherCtrl'});
$routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: 'homeCtrl'});
$routeProvider.when('/campaign', {templateUrl: 'partials/campaign.html', controller: 'campCtrl'});
$routeProvider.when('/quiz', {templateUrl: 'partials/quiz.html', controller: 'quizCtrl'});
$routeProvider.when('/price', {templateUrl: 'partials/price.html', controller: 'priceCtrl'});
$routeProvider.otherwise({redirectTo: '/login'});
}]);
app.filter('range', function() {
return function(input, total) {
total = parseInt(total);
for (var i=1 ; i<=total; i++)
if(i %10 == 0){
input.push(i);
}
return input;
};
});
app.run(function($rootScope, $location, loginService){
var routespermission=['/home', '/campaign', '/quiz', '/price', '/voucher']; //route that require login
$rootScope.$on('$routeChangeStart', function(){
if( routespermission.indexOf($location.path()) !=-1)
{
var connected=loginService.islogged();
connected.then(function(msg){
if(!msg.data) $location.path('/login');
});
}
});
});
The problem was the module declaration, the dependencies needed to be passed in one array and not in two as I did.
var app= angular.module('myApp', ['ngRoute'], ['angularUtils.directives.dirPagination']);
Should be:
var app= angular.module('myApp', ['ngRoute', 'angularUtils.directives.dirPagination']);
Answered by Michael Bromley in http://www.michaelbromley.co.uk/blog/108/paginate-almost-anything-in-angularjs#comment-2122947706
I'm trying to implement a modal from angular ui bootstrap. After I implemented it on my web application, I got an unexpected behavior which is the modal does show up after I clicked the text, but what shows up is not the path that I wanted but rather the navbar of the web app.
Here's the code
index.html
<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<title></title>
<base href='/'>
<!-- load bootstrap from CDN and custom CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<!-- JS -->
<!-- load angular and angular-route via CDN -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-route.js"></script>
<script src="app.js"></script>
<script type="text/javascript" src="controller.js"></script>
</head>
<body>
<header>
<div class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<span class="glyphicon glyphicon-book"></span>Testing App
</div>
<ul class="nav navbar-nav navbar-right" ng-controller="ModalController">
<li>Write</li>
</ul>
</div>
</div>
</header>
<div ng-view></div>
</body>
</html>
app.js
angular.module('MyApp', ['ngRoute', 'ui.bootstrap'])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'HomeController'
});
$locationProvider.html5Mode(true);
});
controller.js
angular.module('MyApp')
.controller('HomeController', function($scope, $location) {
$scope.data = "Hello Angular";
})
.controller('ModalController', function($scope, $location, $modal, $log) {
$scope.items = ['item1', 'item2', 'item3'];
$scope.open = function (size) {
var modalInstance = $modal.open({
templateUrl: 'modal.html',
controller: function() {
},
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
home.html
<div class="container">
<h1>Awesome {{ data }}</h1>
</div>
modal.html (The path that the modal suppose to show);
<h1>Need to show this actually</h1>
The picture, what shows up after i clicked the text that trigger the modal event
Added this:
<script type="text/ng-template" id="modal.html">
<h1>Need to show this actually</h1>
</script>
right after
<ul class="nav navbar-nav navbar-right" ng-controller="ModalController">
and it works in plunker:
http://plnkr.co/edit/bPuemujbTiX7U8AnY607?p=preview