I'm trying to do basic routing in Angular.
My config looks like
app.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/', {
templateUrl: 'home.html', controller: 'loginCtrl'
},
$routeProvider.when('/user_profile/, {
templateUrl: 'user_profile.html', controller: 'UserProfileCtrl'
}
});
When I have a link that goes to user_profile I'm unable to get the $route params.
Go To Profile
In the controller $route.params is undefined.
I tried to make a plnkr but clearly I'm missing something fundamental here
EDIT: $routeParams
I have a module that get's the user info from the server. When I pass in $routeParams is it set to this.
<script type="text/javascript">
angular.module('userFromServer', [])
.service('currentUser', function() {
<% if logged_in %>
this.name = '<%= #User.name %>';
this.id = '<%= #User.id %>'
<% else %>
this.name, this.id = '';
<% end %>
})
</script>
Take a look at this
You can use $routeParams for getting the routing parameteres
Plunker (Non HTML5 Mode)
Plunker (HTML5 Mode)
app = angular.module('MyApp', ['ngRoute']);
app.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: 'home.html',
controller: 'loginCtrl'
})
.when('/user_profile/:user_id', {
templateUrl: 'user_profile.html',
controller: 'UserProfileCtrl'
});
});
app.controller('loginCtrl', function($scope, $routeParams) {
$scope.name = "Hello"
console.log($routeParams);
});
app.controller('UserProfileCtrl', function($scope, $routeParams) {
$scope.name = "UserProfile"
console.log($routeParams);
});
YOu need $route as a parameter in your controller.
app.controller('myCtrl', function($route) {
try to get it from
$routeParams.user_id
... assuming that you are injecting them to controller and you route looks something like this
$routeProvider.when('/user_profile/:user_id, {
templateUrl: 'user_profile.html',
controller: 'UserProfileCtrl'
}
I know this is old, but maybe my solution can still help people.
If your HTML document has a title element in the head element
$Route does not work as expected.
Rather set ALL the Application title's in the app.config function.
From the documentation:
Note that the $routeParams are only updated after a route change completes successfully. This means that you cannot rely on $routeParams being correct in route resolve functions. Instead you can use $route.current.params to access the new route's parameters.
Related
I'm very new to Angular.js.
I've taken the necessary elements from this tutorial on modal windows within Angular.js: http://jasonwatmore.com/post/2016/07/13/angularjs-custom-modal-example-tutorial
Isolated, I can get this code to work, but after porting it to my website, I just can't get it to work.
In Jason's code, he has a file called index.controller.js, and although I've ported this file to my own page, I don't believe it's firing. Here's index.controller.js:
(function () {
angular
.module('app')
.controller('Home.IndexController', Controller);
function Controller(ModalService) {
var vm = this;
vm.openModal = openModal;
vm.closeModal = closeModal;
function openModal(id){
ModalService.Open(id);
}
function closeModal(id){
ModalService.Close(id);
}
}
})();
On my own page, I have all the controllers contained within app.js. Here's how it's laid out:
var app = angular.module('app', ['ngRoute', 'ui.router']);
app.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.hashPrefix('');
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url: '/',
templateUrl: 'pages/main.html',
controller: 'mainController',
controllerAs: 'vm'
})
.state('screenings', {
url: '/screenings',
templateUrl: 'pages/screenings.php',
controller: 'Home.IndexController',
controllerAs: 'vm'
})
...
});
You can see that, in the second .state, I'm attempting to call on the index.controller.js file for this particular partial. For some reason, though, the code under screeningsController (down below) is the code that's firing.
Further down in the same app.js file, I have my controllers:
...
app.controller('screeningsController', ['$scope', '$log', function($scope, $log){
$scope.popup = function() {
// assign a message to the $scope
$scope.message = 'Hello World!';
// use the $log service to output the message in a console
$log.log($scope.message);
};
}]);
...
Is there any way I can somehow integrate what's in the index.controller.js file into my screeningsController in the app.js? I've been trying to get a modal window working on my site for about a week now. Any help is much appreciated.
Start by creating a controller with identifier Home.IndexController. Based on the route configuration this will instantiate when you navigate to "/screenings". Call the popup() function attached to $scope of Home.IndexController via a directive us ng-click for testing. As you have specified controllerAs make sure to reference controller properties and methods prefixed with vm..
You do not need both index.controller.js and app.js both loaded. It looks everything you'd need is defined in app.js, so just make sure that is being loaded in your application. Eventually you'd want to separate these into different files and/or modules as necessary.
Try the following:
Configuration:
var app = angular.module('app', ['ngRoute', 'ui.router']);
app.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.hashPrefix('');
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url: '/',
templateUrl: 'pages/main.html',
controller: 'mainController',
controllerAs: 'vm'
})
.state('screenings', {
url: '/screenings',
templateUrl: 'pages/screenings.php',
controller: 'Home.IndexController',
controllerAs: 'vm'
});
...
});
Home.IndexController:
app.controller('Home.IndexController', ['$log', function($log){
var vm = this;
vm.message = '';
vm.popup = function() {
vm.message = 'foobar';
$log.log(vm.message);
}
}]);
Screenings Template:
<!-- Home.IndexController /screenings template -->
<div>
<button type="button" ng-click="vm.popup()"></button>
</div>
This also assumes you have ui-view specified somewhere in your main template like index.html or equivalent:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body ng-app="app">
<div ui-view></div>
<!-- Vendor and Custom scripts added here -->
</body>
</html>
I am working on an app about routing, my code:
//HTML, I passed a 'test' into routing
Test
<div data-ng-view=""></div>
//Template
<h1>{{res}}</h1>
//Angularjs
var app = angular.module("dictApp", ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/details/:test', {
templateUrl: 'template.html',
controller: 'testCtrl'
});
}]);
app.controller('testCtrl', function ($scope, $routeProvider) {
$scope.res = $routeProvider.test;
});
//The template is displayed as
{{res}}
The template page should display 'test', but I don't know why it didn't work.
Thansk in advance.
'test' parameter should be available in $routeParams.
app.controller('testCtrl', function ($scope, $routeParams) {
$scope.res = $routeParams.test;
});
The service that exposes the route parameters is $routeParams. $routeProvider is the provider used to configure the routes in the app like the one you have done in your code using .when method as well
You need to inject $routeParams and use it instead of $routeProvider
app.controller('testCtrl', function ($scope, $routeParams) {
$scope.res = $routeParams.test;
});
I want to have on the URL of my application like this:
http://localhost:9000/#/?id=XYZ
I don't found how to configure this on angularjs app module
My implementation is like that:
angular.module('APP', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider.when("/?id="+":id", {
templateUrl: "views/sign/sign.html",
controller: "SignCtrl"
});
// $locationProvider.html5Mode(true);
});
but It doesn't work.
You do not have to specify
it will be like
angular.module('APP', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider.when("/", {
templateUrl: "views/sign/sign.html",
controller: "SignCtrl"
});
// $locationProvider.html5Mode(true);
});
and in your SingCtrl.
when you write $routeParam than you will have objects of params which are passed as a query parameter.
so you will get $routePara.id if you pass like ?id=anything
Do not have to worry if you want to catch the query param like ?id=abs&name=test
You can add a "url" attribute to your $routeProvider object.
Something like:
$routeProvider.when("/?id="+":id", {
templateUrl: "views/sign/sign.html",
url: 'the Url you want to use',
controller: "SignCtrl"
});
PS.: I suggest you to use ui-router instead of ngRoute. Check it out later.
I am trying to get rid of the url looking like http://example.com/#/album/0 and have it look more like http://example.com/album/0.
I have the following code
(function() {
var app = angular.module('chp', ['ngRoute', 'projectControllers']);
app.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/directory.html',
controller: 'ProjectsCtrl'
}).
when('/album/:id', {
templateUrl: 'partials/album.html',
controller: 'ProjectDetailCtrl'
}).
otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]);
var projectControllers = angular.module('projectControllers', []);
projectControllers.controller('ProjectsCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.projects = albums;
$scope.filters = { };
}]);
projectControllers.controller('ProjectDetailCtrl', ['$scope', '$routeParams', '$sce',
function($scope, $routeParams, $sce) {
$scope.project = albums[$routeParams.id];
})();
but this is causing my app the break entirely once I add in $locationProvider in the three places shown. Any idea as to why this is not working for me? Also I am including angular-route.js just after jquery and angular.js so that cant be the problem
At a glance it looks all right to me, but you must make sure your server is set up to serve http://example.com/index.html for any route, otherwise it will try to load http://example.com/album/0/index.html before bootstrapping your angular application. What do you see when you enable html5? 404 not found? Console error?
You might also need to add
<base href="/" /> inside <head></head> in your index.html file
I'm pretty new to AngularJS,- in my AngularJS app I have a check in my AppCtrl controller if we have to redirect or not.
.controller('AppCtrl', function($scope, $location) {
if(window.localStorage.getItem("lastStation")) {
$location.path('/app/player/'+window.localStorage.getItem("lastStation"));
}
....
.controller('PlayerCtrl', function($scope, $stateParams) {
alert($stateParams); // This one is alerted TWICE if the $location.path is called in the AppCtrl controller
Hope someone can help with that! ;)
You must have configured routing for your application, like:
yourApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/app/player/:lastLocation', {
templateUrl: 'path_to_your_view',
controller: 'PlayerCtrl'
}).
.....
}]);
Now I got it ;)
.run(function($rootScope, $location) {
if(window.localStorage.getItem("lastStation")) {
$location.path('/app/player/'+window.localStorage.getItem("lastStation"));
}
});
I had to make the check in a .run method.