I'm trying to use two $routeParams , but, appears only the templateUrl of a route. What is the best solution to be able to use $routeParams in all controllers?
Route
angular.module('tareasApp')
.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
console.log("route")
$routeProvider
//These are pages that make up the menu
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/humor', {
templateUrl: 'views/humor.html',
controller: 'HumorCtrl'
})
.when('/nature', {
templateUrl: 'views/nature.html',
controller: 'NatureCtrl'
})
// The $routeParams are to the pages of articles
// Articles in controller HumorCtrl appear perfectly
.when("/:pageName", {
templateUrl: "views/wizard-humor.html",
controller: "HumorCtrl"
})
// Articles in controller NatureCtrl no appear
.when("/:pageName", {
templateUrl: "views/wizard-nature.html",
controller: "NatureCtrl"
})
.otherwise({
redirectTo: '/'
});
});
Controller Humor
angular.module('tareasApp')
.controller('HumorCtrl', function ($scope, $routeParams, $location) {
$scope.pageName = $routeParams.pageName;
$scope.items =[
{
href:'/gold-digger',
img:'digger.jpg',
video:'//www.youtube.com/watch?v=lIruzMwBHJY',
description:'Gold Digger Camel Prank!'
},
{
href:'/woman-abused',
img:'woman.jpg',
video:'//www.youtube.com/watch?v=WXfH3mKqy0A',
description:'Woman Abused In Front Of Cops Prank!'
}
];
$scope.item = $scope.items.filter(function(item) {
return item.href.indexOf($routeParams.pageName) === 1;
})[0];
});
Controller Nature
angular.module('tareasApp')
.controller('NatureCtrl', function ($scope, $routeParams, $location) {
$scope.pageName = $routeParams.pageName;
$scope.items =[
{
href:'/sound-waves',
img:'waves.jpg',
video:'//www.youtube.com/watch?v=OG2eGVt6v2o',
description:'Those Relaxing Sounds of Waves'
},
{
href:'/nature-relaxing-sound',
img:'ocean.jpg',
video:'//www.youtube.com/watch?v=SWR0GdC7_40',
description:'Nature Sounds Relaxing Ocean Sounds'
}
];
$scope.item = $scope.items.filter(function(item) {
return item.href.indexOf($routeParams.pageName) === 1;
})[0];
});
Page wizard-humor.html
<div ng-controller="HumorCtrl">
<img ng-src="images/{{ item.img }}" width="400" height="200" >
<p>{{item.description}}</p>
<iframe width="655" height="400" ng-src="{{ item.video }}" frameborder="0" allowfullscreen></iframe>
</div>
Page wizard-nature.html
<div ng-controller="NatureCtrl">
<img ng-src="images/{{ item.img }}" width="400" height="200" >
<p>{{item.description}}</p>
<iframe width="655" height="400" ng-src="{{ item.video }}" frameborder="0" allowfullscreen></iframe>
</div>
Edited: The problem is the Subdirectory routing not working... I use html5Mode is my <base> tag are thereby <base href="/"> , how to configure correctly for subdirectories work correctly?
You've got twice exactly this same route .when("/:pageName", {..
.when("/:pageName", {
templateUrl: "views/wizard-humor.html",
controller: "HumorCtrl"
})
// Articles in controller NatureCtrl no appear
.when("/:pageName", {
templateUrl: "views/wizard-nature.html",
controller: "NatureCtrl"
})
.otherwise({
redirectTo: '/'
});
change it to :
.when("/humor/:pageName", {
templateUrl: "wizard-humor.html",
controller: "HumorCtrl"
})
// Articles in controller NatureCtrl no appear
.when("/nature/:pageName", {
templateUrl: "wizard-nature.html",
controller: "NatureCtrl"
})
and after that you can have a link like /nature/something or /humor/something
please see demo here http://plnkr.co/edit/fklkUO3YTiXaFYXuDrEz?p=preview
Related
Maybe someone will help me. I write an app in angularjs, I have a file named list.html which retrieves a list of posts from jsonplaceholder and lists them, with a link to the details of the post. In $ routeParams, I pass the id of the selected one and pick it up. Unfortunately, I have no idea how to download the details of a post and display them in the details.html file. If I want to remove something for example, I write for example $ scope.deletePost as a function and give an id, but how to list details I have no idea.
//routing.js
var myApp = angular.module('myApp', ["ngRoute"])
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/test', {
templateUrl: '/event/example.html',
controller: 'exampleController'
}, null)
.when('/list', {
templateUrl: '/event/list.html',
controller: 'exampleController'
}, null)
.when('/test-list', {
templateUrl: '/test/list.html',
controller: 'testController'
}, null)
.when('/test/:id', {
templateUrl: '/test/details.html',
controller: 'testController'
}, null)
}
]);
//controller.js
angular.module('myApp').controller('testController', function ($scope, $http, $routeParams) {
$http.get('https://jsonplaceholder.typicode.com/posts').then(function (response) {
$scope.posts = response.data;
});
$scope.id = $routeParams.id;
});
//details.html
<div data-ng-controller="testController">
{{data}}
</div>
//list.html
<div data-ng-controller="testController">
<ul>
<li ng-repeat="post in posts">
Tytuł: {{post.title}} <a href="#!test/{{post.id}}" >Show</a>
</li>
</ul>
</div>
Check out this plunkr.
You just need to pass the details using ng-href and then catch in the controller using $routeParams. I hope this would help you with what you were looking for.
var app = angular.module( 'mainApp', ['ngRoute'] );
app.config( function( $routeProvider ) {
$routeProvider
.when( '/main', {
templateUrl: 'list.html',
controller: 'listCtrl'
})
.when('/detail/:id', {
templateUrl: 'detail.html',
controller: 'detailCtrl'
})
.otherwise({
redirectTo: '/main'
});
});
app.controller( 'listCtrl', function( $scope, $http) {
$http.get('https://jsonplaceholder.typicode.com/posts')
.then(function(res){
$scope.data = res.data;
})
});
app.controller( 'detailCtrl', function( $scope,$http, $routeParams) {
$scope.id = $routeParams.id;
$http.get('https://jsonplaceholder.typicode.com/posts/'+$scope.id)
.then(function(res){
$scope.data = res.data;
})
});
I ask them to help solve this problem, follows the code :
Controller
angular.module('tareasApp')
.controller('HumorCtrl', function ($scope, $route, $location) {
$scope.pageName = $route.current.params.pageName;
$scope.items =[
{
href:'/humor/smile-today',
img:'smile.jpg',
descricao:'Those Relaxing Sounds of Waves'
}
];
});
angular.module('tareasApp')
.controller('NewsCtrl', function ($scope, $route, $location) {
$scope.pageName = $route.current.params.pageName;
$scope.items =[
{
href:'/news/news-today',
img:'news.jpg',
descricao:'Those Relaxing Sounds of Waves'
}
];
});
App.js
myApp.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
title: 'Home Page',
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/humor/:pageName', {
templateUrl: 'views/wizard.html',
controller: 'HumorCtrl'
})
.when('/news/:pageName', {
templateUrl: 'views/wizard.html',
controller: 'NewsCtrl'
})
.otherwise({
redirectTo: '/'
});
});
When I type any route that does not exist right after the bar, eg:
domain.com/hhhoedr
returns to the start page .
The problem is in the sub-directory, which contains the $routeParams, typing a page that does not exist , eg:
domain.com/humor/hhhoedr
is not redirecting to index.html or to 404.html.
I would like to adapt this code, I found in another answer, to my app.
myApp.constant('EXISTING_PAGES', [
'page1',
'page2',
...
]);
resolve: {
exists: function ($location, $route) {
if (EXISTING_PAGES.indexOf($route.current.params.page) === -1) {
$location.path('/error/404');
}
return true;
}
}
.when('/error/404', {
templateUrl: '404.html'
})
.otherwise({
redirectTo: '/error/404'
});
how can I do it?
When you are typing any route e.g-domain.com/hhhoedr,It is returning to starting page because check you last part of your code,you are setting it like below.
.otherwise({
redirectTo: '/'
});
If you will set anything except from your all .when part it will simple redirect to the starting page.Try to set it for redirecting to any other page as per your requirement.
Ok,Now you can write it like below.
.otherwise({
redirectTo: '/here give your destination path(e.g-404.html...etc)'
});
I would like to direct the pages of templateUrl , en route, to the wizard.html page. To filter fixed items to their respective pages , I use: | filterBy: ['href']:'/sound-waves' , for example. How could insert the items dynamically on one page ?
angular.module('tareasApp')
.controller('NatureCtrl', function ($scope, $routeParams, $sce, $location, $anchorScroll) {
$scope.items =[
{
href:'/sound-waves',
img:'waves.jpg',
video:'//www.youtube.com/watch?v=OG2eGVt6v2o',
description:'Those Relaxing Sounds of Waves'
},
{
href:'/nature-relaxing-sound',
img:'ocean.jpg',
video:'//www.youtube.com/watch?v=SWR0GdC7_40',
description:'Nature Sounds Relaxing Ocean Sounds'
}
];
});
Page wizard.html
<div ng-controller="NatureCtrl">
<div ng-repeat="item in items | filterBy: ['href']: ''" >
<img ng-src="images/{{ item.img }}" width="400" height="200" >
<p>{{item.description}}</p>
<iframe width="655" height="400" ng-src="{{ item.video }}" frameborder="0" allowfullscreen></iframe>
</div>
</div>
Route
angular.module('tareasApp')
.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/sound-waves', {
templateUrl: 'views/wizard.html',
controller: 'NatureCtrl'
})
.when('/nature-relaxing-sound', {
templateUrl: 'views/wizard.html',
controller: 'NatureCtrl'
})
.otherwise({
redirectTo: '/'
});
});
The goal is to avoid having multiple pages with the same structure.
Edited: The names of the pages are not in sequence so no . I had put to make it easier to understand . ( Had written as: page-one , page-two changed to sound-waves, nature-relaxing-sound )
Edited: Put the ...controller('NatureCtrl', function... involving the items array for better understanding.
You are right that creating a route for each URL is the wrong way to go, which is why $routeProvider supports route params.
You can define your route as follows:
$routeProvider
.when("/:pageName", {
templateUrl: "views/wizard.html",
controller: "NatureCtrl"
});
and pageName will be available as a $routeParam.pageName:
.controller("NatureCtrl", function($scope, $routeParams){
// ... pageName could be: "sound-waves" or "nature-relaxing-sound"
$scope.pageName = $routeParams.pageName;
});
If the items are coming from a service, say ItemsService, you could also use the resolve property to obtain the items and even pre-filter them as they are coming from the service, as an inject-able parameter for your controller. Here's how it could look like:
$routeProvider
.when("/:pageName", {
templateUrl: "views/wizard.html",
resolve: {
item: function(ItemService, $route){
// $routeParams here would not yet have the params for this route
return ItemsService.getItemsForPage($route.current.params.pageName);
}
},
controller: function($scope, item){
$scope.itemForThePage = item;
}
})
When using parameters in ngRoute and accessing the URL directly (not through a link inside the site), the CSS does not load. All my routes work perfectly except for /chef/:id. I used yeoman's angular generator, and I'm running things using grunt serve.
Here's my Route code:
angular
.module('agFrontApp', [
'configuration',
'LocalStorageModule',
'ngCookies',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: '../views/main_view.html',
controller: 'MainCtrl',
controllerAs: 'MainCtrl',
})
.when('/login', {
templateUrl: '../views/login_view.html',
controller: 'LoginCtrl',
controllerAs: 'login',
})
.when('/chefs', {
templateUrl: '../views/chef_list_view.html',
controller: 'ChefListController',
controllerAs: 'chefs',
})
.when('/chef/:id', {
templateUrl: '../views/chef_detail_view.html',
controller: 'ChefDetailController',
controllerAs: 'chef'
})
.when('/receitas', {
templateUrl: '../views/recipe_list_view.html',
controller: 'RecipeListController',
controllerAs: 'recipe'
})
.when('/perfil', {
templateUrl: '../views/perfil_view.html',
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
});
And here's the controller for /chef/:id:
'use strict';
(function() {
function ChefDetailController($routeParams, $scope, $log, Chefs) {
var vm = this;
Chefs.getChef($routeParams.id)
.then(function(data) {
$log.log('success');
})
.fail(function(data) {
$log.log('something went wrong');
});
}
angular.module('agFrontApp')
.controller('ChefDetailController',
[ '$routeParams', '$scope', '$log', 'Chefs', ChefDetailController]);
})();
What am I doing wrong?
Edit:
Here's chef_detail_view.html: http://pastebin.com/bL5ST01N
You're very likely loading your CSS using a relative url like so
<link rel="stylesheet" href="styles/style.css" />
The problem is in html5mode your chef url is /chef/123 So the browser is trying to load your CSS from
/chef/styles/style.css You'll want to either turn off html5mode or change your stylesheet href to be root relative (e.g. /styles/style.css)
I am trying to implement html5's pushstate instead of the # navigation used by Angularjs. I have tried searching google for an answer and also tried the angular irc chat room with no luck yet.
This is my controllers.js:
function PhoneListCtrl($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
}
function PhoneDetailCtrl($scope, $routeParams) {
$scope.phoneId = $routeParams.phoneId;
}
function greetCntr($scope, $window) {
$scope.greet = function() {
$("#modal").slideDown();
}
}
app.js
angular.module('phoneapp', []).
config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/phones', {
templateUrl: 'partials/phone-list.html',
controller: PhoneListCtrl
}).
when('/phones/:phoneId', {
templateUrl: 'partials/phone-detail.html',
controller: PhoneDetailCtrl
}).
otherwise({
redirectTo: '/phones'
});
}])
Inject $locationProvider into your config, and set $locationProvider.html5Mode(true).
http://docs.angularjs.org/api/ng.$locationProvider
Simple example:
JS:
myApp.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/page1', { template: 'page1.html', controller: 'Page1Ctrl' })
.when('/page2', { template: 'page2.html', controller: 'Page2Ctrl' })
});
HTML:
Page 1 | Page 2