I am new to UI-Router and am struggling to get my controller invoked. I am using an abstract state as the parent and it does not seem to call the controller. Below is a simplified version of my code.
I binded $stateChangeError onto the console and am not getting an error on the console. I added onEnter and OnExit attributes to my state and only the onEnter function gets called (not included below).
index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />'); </script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.3.x" src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.14/angular-ui-router.js" ></script>
<script src="app.js"></script>
</head>
<body>
<div ui-view="navbar" ></div>
<div class="container">
<div ui-view="content" ></div>
</div>
<p>We are on the homepage.</p>
</body>
</html>
App.js
var app = angular.module('plunker', ['ui-router']);
app.config(function ($stateProvider, $urlRouteProvider) {
$urlRouteProvider.otherwise("/");
$stateProvider.state('site', {
abstract: true,
views: {
'navbar#': {
template: '<p>This is the {{nav}}</p>',
controller: 'NavBarCtrl'
}
}
});
});
app.config(function($stateProvider) {
$stateProvider
.state('home', {
parent: 'site',
url: '/',
views: {
'content#': {
template: '<p>This is the {{content}}</p>',
controller: 'MainCtrl'
}
}
});
});
app.controller('NavBarCtrl', function($scope) {
$scope.nav = 'Navbar'
});
app.controller('MainCtrl', function($scope) {
$scope.content = 'content'
});
There is a working example
There are two issues. Firstly we have to reference correct module:
// instead of this
// var app = angular.module('plunker', ['ui-router']);
// we need this
var app = angular.module('plunker', ['ui.router']);
And we have to use proper names of the '$urlRouterProvider'
// instead of this
app.config(function ($stateProvider, $urlRouteProvider) {
$urlRouteProvider.otherwise("/");
// we need this
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
Check it working here
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 using ui router and angular js so when I test the app, I just get a blank screen with an injector:module error. This is the link to the error:
http://errors.angularjs.org/1.3.11/$injector/modulerr?p0=myApp&p1=Error%3A%…dflare.com%2Fajax%2Flibs%2Fangular.js%2F1.3.11%2Fangular.min.js%3A17%3A350
Here is my app.js code:
var app = angular.module('myApp', ['ui.router', 'firebase']);
// Creating fireref instance
app.factory('FireRef', function($firebase){
var ref = new Firebase('https://dablog.firebaseio.com/');
return ref;
});
// Creating fireauth instance
app.factory('FireAuth', function($firebaseAuth){
var ref = new Firebase('https://dablog.firebaseio.com/');
return $firebaseAuth(ref);
});
app.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/site/home');
$stateProvider
.state('site', {
url: '/site',
templateUrl: 'partials/site.html'
})
.state('site.home', {
url: '/home',
templateUrl: 'partials/home.html'
})
.state('site.about', {
url: '/about',
templateUrl: 'partials/about.html'
})
.state('site.projects', {
url: '/projects',
templateUrl: 'partials/projects.html'
})
.state('site.blog', {
url: '/blog',
templateUrl: 'partials/blog.html'
// controller: 'BlogCtrl'
})
.state('site.login', {
url: '/login',
templateUrl: 'partials/login.html'
// controller: 'LoginCtrl'
})
.state('site.newpost', {
url: '/newpost',
templateUrl: 'partials/newpost.html',
// controller: 'NewPostCtrl'
})
.state('site', {
url: '/contact',
templateUrl: 'partials/contact.html'
});
})
Here is my blog.js file where it says "app is not defined":
'use strict'
app.controller('BlogCtrl', function($scope, $firebase, $firebaseArray, FireRef, $state){
var data = $firebaseArray(FireRef);
$scope.posts = data;
$scope.$watch('posts', function(newValue, oldValue){
$scope.posts = $sce.trustAsHtml(data);
})
$scope.login = function() {
$state.go('site.login');
}
$scope.newPost = function(){
$state.go('site.newPost');
}
});
Here is my index.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8">
<title>Portfolio</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Angular -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular.min.js"></script>
<!-- Angular UI Router -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.13/angular-ui-router.js"></script>
<!-- Angular Animate -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.13/angular-animate.min.js"></script>
<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- Bootstrap -->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.min.js"></script>
<!-- Firebase -->
<script src="https://cdn.firebase.com/js/client/2.2.0/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.9.1/angularfire.min.js"></script>
<!-- Controllers -->
<script src="js/controllers/BlogCtrl.js"></script>
<script src="js/controllers/LoginCtrl.js"></script>
<script src="js/controllers/NewPostCtrl.js"></script>
<!-- App -->
<script src="js/app.js"></script>
<!-- Styling -->
<link rel="stylsheet" type="text/css" href="css/styles.css">
<link rel="stylsheet" type="text/css" href="css/animate.css">
</head>
<body ng-app="myApp">
<div ui-view></div>
</body>
</html>
You have declared 'use strict', so the app variable is undefined. You need to add
var app = angular.module('myApp');
to the top of BlogCtrl.js
Also, move <script src="js/app.js"></script> so that it's before the controller scripts in index.html. Because you load app.js after BlogCtrl.js, the module defined in app.js is not available in BlogCtrl.js.
I don't have enough reputation to comment, but I do want to add information: do not add var app = angular.module('myApp', []) in blog.js, because the brackets initialize a new app, so Angular will think you're creating a new app and will throw an error, since 'myApp' already exists. Be sure to use var app = angular.module('myApp') instead. Also be sure to link the the .js file in your index file after Angular has been loaded.
I think you need to include this line at the top of blog.js:
var app = angular.module('myApp');
Edited to remove the second parameter: , [].
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 });
}
}
});
});
I'm just trying UI Router for the first time. This is my very simple attempt. So I would now expect, that just the header would display. But the page keeps empty. What am I doing wrong?
<!doctype html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.14/angular-ui-router.min.js"></script>
<script>
var app = angular.module('myApp', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state('index', {
template: '<h1>Header</h1>'
});
});
</script>
</head>
<body>
<main ui-view></main>
</body>
</html>
You have to set - in your example - $urlRouterProvider:
var app = angular.module('myApp', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider.state('index', {
url : '/',
template: '<h1>Header</h1>'
});
});
If you're expecting a state to activate when on a specific url (from pushState or http) you need to specify the url.
var app = angular.module('myApp', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state('index', {
url : '/',
template: '<h1>Header</h1>'
});
});
You have to set a blank url state for $stateProvider
var app = angular.module('myApp', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('index', {
url : '',
template: '<h1>Header</h1>'
});
});
Plnkr: http://plnkr.co/edit/n3uX2SMR0puNROzRePOO
i try to write an angular app using best code practice and i got to this:
index.html file contain :
<!DOCTYPE html>
<html ng-app='hrsApp'>
<head>
<title>Hrs app</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body ng-controller="homeCtrl">
<div class='container'>
<div ng-view></div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular-route.min.js"></script>
<script src='app.js'></script>
<script src='js/controllers/homeCtrl.js'></script>
<script src='js/controllers/avCtrl.js'></script>
</body>
</html>
Main file: app.js:
angular.module('home', []);
angular.module('av', []);
// Declare app level module which depends on filters, and services
angular.module('hrsApp', [
'hrsApp.controllers',
'hrsApp.services',
'hrsApp.directives',
'hrsApp.filters',
// AngularJS
'ngRoute',
// All modules are being loaded here but EMPTY - they will be filled with controllers and functionality
'home',
'av'
]);
// configure our routes
angular.module('hrsApp').config([
'$routeProvider',
function ($routeProvider) {
'use strict';
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'views/home.html',
controller: 'homeCtrl'
})
// route for the about page
.when('/av', {
templateUrl: 'views/av.html',
controller: 'avCtrl'
})
// route for the contact page
.otherwise({
redirectTo: '/'
});
}
]);
Then i added the home controller:
/*global angular*/
angular.module('home').controller('homeCtrl', [
'$scope',
function ($scope) {
'use strict';
$scope._init = function () {
$scope.message = "welcome to Home Ctrl";
};
// DESTRUCTOR
$scope.$on('$destroy', function () {
});
// Run constructor
$scope._init();
$scope.log('info', '[HomeCtrl] initialized');
}
]);
and home template that for the moment contain only a binding to the message variable:
<div>{{message}}</div>
When i try to run the application i got : Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.0/$injector/modulerr?p0=hrsApp&p1=Error%3A%…googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.0%2Fangular.min.js%3A18%3A3) angular.js:38
Any idea what i do wrong?
From your code I can see that you have injected modules that you did not declared.
in order todo so you must add the following lines to your code:
angular.module('hrsApp.controllers',[]);
angular.module('hrsApp.services',[]);
angular.module('hrsApp.directives',[]);
angular.module('hrsApp.filters',[]);