I am getting undefined for $routeParams. Here is my code:
var ngAddressBook = angular.module('ngAddressBook', ['ngRoute']);
ngAddressBook.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'views/list.html',
controller: 'ngAddressListController'
}).
when('/add', {
templateUrl: 'views/add.html',
controller: 'ngAddressListController'
}).
when('/details/:id', {
templateUrl: 'views/details.html',
controller: 'ngAddressDetailsController'
});
}]);
// add a controller to it
ngAddressBook.controller('ngAddressListController', ['$scope', function ($scope)
{
$scope.contacts = [
{id:1,first_name:'Jane', last_name:'Doe','Phone':'123-456789','Email':'jane#example.com'},
{id:2,first_name:'Jhon', last_name:'Doe','Phone':'123-456789','Email':'jhon#example.com'}
];
$scope.getTotalContacts = function () {
return $scope.contacts.length;
};
}]);
ngAddressBook.controller('ngAddressDetailsController', ['$scope', function ($scope,$routeParams)
{
alert($routeParams);
$scope.id = $routeParams.id;
}]);
index.html
<!doctype html>
<html ng-app="ngAddressBook">
<head>
<title>Ng Addressbook</title>
<link href="main.css" rel="stylesheet" media="screen" />
</head>
<body>
<div ng-controller="ngAddressListController">
<div id="container">
<h1>Ng Address Book</h1>
<div id="content" ng-view>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
<script src = "angular-route.min.js"></script>
<script src="main.js"> </script>
</body>
</html>
There is a problem in controller parameter injection. You have not added $routeParams in your array injection list.
ngAddressBook.controller('ngAddressDetailsController', ['$scope','$routeParams', function ($scope,$routeParams)
{
alert($routeParams);
$scope.id = $routeParams.id;
}]);
As I found this on top on google:
apart from the missing injection - asign the object $routeParams and not the Key $routeParams.id
I found the explination here (from Sander Elias)
ngAddressBook.controller('ngAddressDetailsController', ['$scope','$routeParams', function ($scope,$routeParams)
{
$scope.id = $routeParams
alert($routeParams);
}]);
Related
Scenario is,
Im new to AngularJS and making an AngularJS with AngularFire, I have defined my routing bye using $routeProvider ,see below
var appMainModule = angular.module('appMain', [ 'firebase','ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/', { templateUrl: '/Templates/CustomerLogin.html', controller: 'HomeCtrl' });
$routeProvider.when('/customer/home', { templateUrl: '/Templates/CustomerHome.html' , controller:'ForLogout'});
$routeProvider.when('/customer/singup', { templateUrl: '/Templates/CustomerSinup.html', controller: 'RegisterCtrl' });
$routeProvider.when('/dashboard/godash', { templateUrl: '/Templates/dashboard.html', controller: 'DashboardCtrl' });
$routeProvider.when('/customer/list', { templateUrl: '/Templates/CustomerList.html', controller: 'customerListViewModel' });
$routeProvider.when('/customer/detail', { templateUrl: '/Templates/CustomerDetail.html', controller: 'customerDetailViewModel' });
$routeProvider.when('/customer/googlemap', { templateUrl: '/Templates/GoogleMap.html', controller: 'MapCtrl' });
// $routeProvider.when('/customer/postdata', { templateUrl: '/Templates/CustomerPostData.html', controller: 'AddPostCtrl' });
$routeProvider.when('/customer/getdata', { templateUrl: '/Templates/CustomerGetData.html', controller: 'GetCtrl', reloadOnSearch: false });
$routeProvider.when('/victim/getdata', { templateUrl: '/Templates/RiskVictimDetail.html', controller: 'VictimGetCtrl' });
$routeProvider.otherwise({ redirectTo: '/' });
$locationProvider.html5Mode(true);
});
this is my login controller
appMainModule.controller('HomeCtrl', ['$scope', '$location', 'CommonProp', '$firebaseAuth', function ($scope, $location,CommonProp, $firebaseAuth) {
var firebaseObj = new Firebase("FireaseURL/");
loginObj = $firebaseAuth(firebaseObj);
$scope.user = {};
var login = {};
$scope.SignIn = function (e) {
login.loading = true;
e.preventDefault();
var username = $scope.user.email;
var password = $scope.user.password;
loginObj.$authWithPassword({
email: username,
password: password
})
.then(function (user) {
//Success callback
// alert('Authentication successful');
login.loading = false;
$location.path('/dashboard/godash')
}, function (error) {
//Failure callback
alert('Authentication failure');
});
}
}])
my problem is that, when I refresh my login page by browser refresh, it refreshes successfully, but after login when refresh any page it gives me error
Page Not Found
my HTML:
<!DOCTYPE html>
<html data-ng-app="sampleApp">
<head>
<title>My new Project</title>
<meta charset="utf-8" />
<!-- AngularJS -->
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<!-- Firebase -->
<script src="https://cdn.firebase.com/js/client/2.2.4/firebase.js"></script>
<!-- AngularFire -->
<script src="https://cdn.firebase.com/libs/angularfire/1.2.0/angularfire.min.js"></script>
<script src="Scripts/App.js"></script>
<base href="/" />
</head>
<body ng-view>
</body>
</html>
If you configure $location to use html5Mode (history.pushState), you need to specify the base URL for the application with a <base href=""> tag or configure $locationProvider to not require a base tag by passing a definition object with requireBase:false to $locationProvider.html5Mode():
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
From : https://docs.angularjs.org/error/$location/nobase
Be sure to check all relative links, images, scripts etc. Angular requires you to specify the url base in the head of your main html file () unless html5Mode.requireBase is set to false in the html5Mode definition object passed to $locationProvider.html5Mode(). With that, relative urls will always be resolved to this base url, even if the initial url of the document was different.
From : https://code.angularjs.org/1.3.14/docs/guide/$location
Simple example:
Index.html
<!DOCTYPE html>
<html data-ng-app="appMain">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<script src="script.js"></script>
<base href="/" />
</head>
<body ng-view>
</body>
</html>
script.js
var appMainModule = angular.module('appMain', ['ngRoute'])
.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: '/Templates/CustomerLogin.html',
controller: 'HomeCtrl'
});
$routeProvider.when('/customer/home', {
templateUrl: '/Templates/CustomerHome.html',
controller: 'ForLogout'
});
$routeProvider.when('/dashboard/godash', {
templateUrl: '/Templates/dashboard.html',
controller: 'DashboardCtrl'
});
$routeProvider.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
});
appMainModule.controller('HomeCtrl', ['$scope', '$location', function($scope, $location) {
$scope.godash = function(e) {
$location.path('/dashboard/godash')
}
}]);
appMainModule.controller('DashboardCtrl', ['$scope', '$location', function($scope, $location) {
$scope.home = function(e) {
$location.path('/customer/home')
}
}]);
appMainModule.controller('ForLogout', ['$scope', '$location', function($scope, $location) {
$scope.home = function(e) {
$location.path('/')
}
}]);
/Templates/CustomerLogin.html
<div>
<button ng-click="godash()">/dashboard/godash</button>
</div>
/Templates/CustomerHome.html
<div>
<button ng-click="home()">/</button>
</div>
/Templates/dashboard.html
<div>
<button ng-click="home()">/customer/home</button>
</div>
I'm attempting to make a simple Hello World page with an inline template defined as home.html. The routing used is ui.router, and when the code is run I receive an infinite loop of
GET /home.html 404 0.868 ms - 1076
which indicates to me that angular can't find the home.html template that was defined.
app.js
var app = angular.module('HelloWorld', ['ui.router']);
app.controller('MainCtrl', [
'$scope',
'posts',
function($scope, posts){
$scope.test = 'Hello world!';
$scope.posts = posts.posts;
$scope.addPost = function(){
if(!$scope.title || $scope.title === '') { return; }
$scope.posts.push({
title: $scope.title,
link: $scope.link,
upvotes: 0
});
$scope.title = ''; //Set title to empty
$scope.link = ''; // Set link to empty
};
$scope.incrementUpvotes = function(post) {
post.upvotes += 1;
};
}]);
app.factory('posts', [function(){
var o = {
posts: [
{title: 'post 1', upvotes: 5}
]
};
return o;
}]);
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home.html',
controller: 'MainCtrl'
});
$urlRouterProvider.otherwise('home');
}]);
index.ejs
<!DOCTYPE html>
<html ng-app="HelloWorld">
<head>
<title>Hello World</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<script src="javascripts/app.js"></script>
<style> .glyphicon-thumbs-up { cursor:pointer } </style>
</head>
<body>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view>
</div>
</div>
<script type="text/ng-template" id="home.html">
<div class="page-header">
<h1>Hello World</h1>
</div>
</script>
</body>
</html>
I can't spot what seems to be going wrong in the code. I've also tried variations using /home.html in both the app config and html to no avail. I could use some insight on how I missed up the configuration/inline template.
If this is exactly your code you have a missing " in id of template. See below for correction
<script type="text/ng-template" id="home.html">
Your code is working fine for me. To further test it I added the following to the html:
<a ui-sref='home'>Home</a>
<a ui-sref='about'>About</a>
....
<script type="text/ng-template" id="about.html">
<div class="page-header">
<h1>About</h1>
</div>
</script>
I then added the following route to the javascript:
.state('about', {
url: '/about',
templateUrl: 'about.html',
controller: 'MainCtrl'
});
This adds links to the top left allowing you to switch views. You can see the working code at http://codepen.io/amartin007/pen/rLOvqa
Referring to the code given below, I would like to be able to load viewTeam URL into ng-view from the showTeam() function. How can I do this?
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.min.js"></script>
<script>
var teamApp = angular.module("teamApp", ['ngRoute']);
teamApp.controller('teamController', function($scope, $http) {
$http
.get('/teams')
.success(function(response) {
$scope.teams = response;
}
);
var showTeam = function(id) {
}
});
teamApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/addTeam', {
templateUrl: 'addTeam.htm',
controller: 'AddTeamController'
}).
when('/viewTeam', {
templateUrl: 'viewTeam.htm',
controller: 'ViewTeamController'
}).
otherwise({
redirectTo: '/addTeam'
});
}]);
teamApp.controller('AddTeamController', function($scope) {
});
teamApp.controller('ViewTeamController', function($scope, $routeParams) {
});
</script>
</head>
<body>
<div ng-app = "teamApp" ng-controller="teamController">
<button ng-click="newTeam()">new</button>
<div ng-repeat="team in teams" >
Name: {{team.name}}
<br />
Description: {{team.description}}
<br />
<button ng-click="showTeam(team.id)">show</button>
</div>
<div ng-view></div>
<script type = "text/ng-template" id = "addTeam.htm">
<h2> Add Team </h2>
To be implemented later.
</script>
<script type = "text/ng-template" id = "viewTeam.htm">
Name: {{team.name}}
Description: {{team.description}}
</script>
</div>
</body>
</html>
You need to change your $routeprovider for viewTeam to expect an id parameter. Then get that id in the viewTeamController using routeparams. Here is how you do it. Just follow the pattern in the script below:
<script>
var teamApp = angular.module("teamApp", ['ngRoute']);
teamApp.controller('teamController', function($scope, $http,$location) {
$http
.get('/teams')
.success(function(response) {
$scope.teams = response;
}
);
var showTeam = function(id) {
$location.url("#/viewTeam/" + id);//there are other means as well.
}
});
teamApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/addTeam', {
templateUrl: 'addTeam.htm',
controller: 'AddTeamController'
}).
when('/viewTeam/:id', {
templateUrl: 'viewTeam.htm',
controller: 'ViewTeamController'
}).
otherwise({
redirectTo: '/addTeam'
});
}]);
teamApp.controller('AddTeamController', function($scope) {
});
teamApp.controller('ViewTeamController', function($scope, $routeParams) {
alert($routeParams.id);//you get the route params here.
});
</script>
When navigating from view:
<a href="#viewTeam/45">
In your case:
<a href="#viewTeam/{{team.id}}"> //to navigate from view.
In your teamController do this -
var showTeam = function(id) {
$location.path('/viewTeam.htm').search({'id': id});
}
In ViewTeamController you can get id like this
//Get id from url params
$location.search('id');
you can use $location to change the path
$scope.showTeam = function(view){
$location.path("/viewTeam"); // path not hash
}
I'm teaching myself some AngularJS and have made some progress.
The routing on the following project doesn't seem to work but I don't know what I'm doing wrong. I use WebStorm.
I did an exercise (the adding names part) and now I'm trying to show what's within the views on the index page but this doesn't seem to work..
Index.html:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="angular/angular.js"></script>
<script src="angular/angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="myController as ctrl">
<h1>Lijst met namen</h1>
<input type="text" placeholder="voornaam..." ng-model="ctrl.voornaam">
<input type="text" placeholder="achternaam..." ng-model="ctrl.name">
<input type="button" value="Persoon toevoegen" ng-click="ctrl.addNaam()">
<ul>
<li ng-repeat="person in ctrl.personen">
{{person.name}} {{person.voornaam}}
</li>
</ul>
</div>
<div role="navigation">
<nav>
Home
About us
Contact us
</nav>
</div>
<div ng-view></div>
<script src="controller.js"></script>
<script src="aboutController.js"></script>
<script src="contactController.js"></script>
<script src="homeController.js"></script>
</body>
</html>
App.js:
angular.module('myApp',['ngRoute']).config(moduleConfig);
//Inject dependencies
moduleConfig.$inject = ['$routeProvider'];
//routes configureren
function moduleConfig($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/home.html',
controller: 'homeController',
controllerAs: 'homeCtrl'
})
.when('/home', {
templateUrl: 'views/home.html',
controller: 'homeController',
controllerAs: 'homeCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'aboutController',
controllerAs: 'aboutCtrl'
})
.when('/contact', {
templateUrl: 'views/contact.html',
controller: 'contactController',
controllerAs: 'contactCtrl'
})
.otherwise({
redirectTo: '/'
});
} })();
Controller.js:
angular.module('myApp', []).controller('myController', myController);
function myController(){
var vm = this;
vm.personen = [
{name: 'Schrooten', voornaam: 'Mathias'}
];
vm.addNaam = function(){
var newName = {
voornaam: this.voornaam,
name: this.name
};
this.personen.push(newName);
window.alert('Persoon toegevoegd!')
}
}
aboutController:
angular.module('myApp').controller('aboutController', aboutController);
function aboutController(){
this.msg = 'Hello';
}
2 other controllers look almost the same (contactController.js and homeController.js)
views:
about.html:
<div>
<p>About us: ....</p>
<input type="text">
</div>
Same for 2 other views.
this line angular.module('myApp', []) initializes a module.
So basically you have to initialize once.
then you can use it like this angular.module('myApp')
so this in you code:
angular.module('myApp', []).controller('myController', myController);
has to become like the line below because you already have myApp module defined:
angular.module('myApp').controller('myController', myController);
The angular.module('myApp') is a redundant code in your codebase. creating angular modules everywhere is the incorrect thing here. Create it once, store it in a variable, lets say 'app' and use it everywhere else.
Like as follows:
in app.js :
var app = angular.module('myApp', ['ngRoute']);
in route.js :
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'login.html'
})
.when('/home', {
templateUrl : 'main.html',
controller: 'myController'
})
.otherwise({
redirectTo: '/'
});
});
In Controller.js :
app.controller('myController', myController);
function myController(){
var vm = this;
vm.personen = [
{name: 'Schrooten', voornaam: 'Mathias'}
];
vm.addNaam = function(){
var newName = {
voornaam: this.voornaam,
name: this.name
};
this.personen.push(newName);
window.alert('Persoon toegevoegd!')
}
}
You can refer to one of my github repositories to understand a basic angular framework that uses template routing for a single page application here.
Try to do:
angular.module('myApp',['ngRoute']).config(['$routeprovider', moduleConfig]);
And then you should be able to get rid of the .$inject you call.
From your code as first I see this line looks to be wrong, when you register your 'myController' controller. There you are using angular.module('myApp', []) hovewer in App.js there is the 'myApp' module created. In 'Cotnroller.js' use angular.module('myApp').controller(...) without brackets. Currenlty in Controller.js you overwrite the 'myApp' module.
I am trying to change the route Params in my controller using the updateParams method, but for some reason I am getting an error:
TypeError: $route.updateParams is not a function.
In my controller I have:
App.controller('AddController', ['$scope', '$routeParams', '$route',
function ($scope, $routeParams, $route)
{
$route.updateParams({child: 'all'});
}]);
And this is my routing configuration:
App.config([
'$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/', {
redirectTo: '/'
})
.when('/:page/:child*', {
templateUrl: function($routeParams) {
return 'views/'+ $routeParams.page + '/' + $routeParams.child + '.html';
},
})
.otherwise({
redirectTo: '/'
});
}]);
I have no idea why can't I use the updateParams method, or what am I doing wrong here?
For anyone that is stuck on this like I was, I had to get the 1.4.8 version of angular AND the 1.4.8 version of angular-route to use $route.updateParams
plnkr
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#*" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script data-require="angular-route#*" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="routeUpdateParams">
<h1>Hello Plunker!</h1>
Click to load the test view
<div ng-view></div>
</body>
</html>
var app = angular.module("routeUpdateParams", ["ngRoute"]);
app.config(function($routeProvider ){
$routeProvider.when("/test/:testId", {
template:"<h3>test:{{testId}}</h3><button ng-click='reloadRoute()'>reloadRoute</button>",
controller: function($scope,$route,$routeParams) {
$scope.testId = $routeParams.testId;
$scope.reloadRoute = function(){
console.log($route)
$route.updateParams({ testId: 5 });
}
}
});
});