How to get parameter from angular with $routeParams - angularjs

I want to get some posts by category id. So I need to get a parameter from URL in angular but somehow it seems the route does not call the right controller when I put :id as the parameter in the category route. Here is the controller looks like.
.config(['$routeProvider',function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "home.html",
controller: "mainController"
})
.when('/category/:id', {
templateUrl: "category.html",
controller: "categoryController",
});
}])
And this is the controller.
.controller('categoryController',['$scope','$http','$ionicModal','$routeParams','$location', function ($scope, $http, $ionicModal,$routeParams,$location) {
var id = $routeParams.id;
var httpUrl = 'http://localhost/myapp/';
var url = httpUrl + 'webservices/get_posts_by_category?cat_id=' + id;
$http.get(url).then(function (result) {
console.log(result);
$scope.posts = result.data;
})
But it shows nothing, event it doesn't fire the console.log(result). Looks like it routes to the wrong controller. I just don't know why. What did I miss?

Related

In Angular, can view be loaded in code?

Very simply, after an API call, depending on the return value, how is the appropriate view loaded? Consider having
search.html
views/found.html
views/notfound.html
Search's controller makes an AJAX call to a service and gets a good or bad result. Now I want the appropriate view to load, without user having to click. I just can't figure out how to do this and have looked at scores of routing/view examples. I'm using HTML5 mode.
app.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'search.html',
controller: 'searchCtrl'
})
.when('found', {
templateUrl: 'views/found.html',
controller: 'foundCtrl'
})
.when('notFound', {
templateUrl: 'views/notFound.html',
controller: 'notFoundCtrl'
})
.otherwise({
templateUrl: 'search.html',
controller: 'searchCtrl'
});
$locationProvider.html5Mode({
enabled: true,
requiredBase: true
});
And in the controller ..
$scope.post = function (requestType, requestData) {
var uri = 'Search/' + requestType;
$http.post(uri, requestData)
.success(function (response) {
$scope.searchResult.ID = response.ID;
$scope.searchResult.Value = response.Value;
// how is the view/route loaded without a user click?
'found';
return true;
}).error(function (error) {
// how is the view/route loaded without a user click?
'notFound';
return false;
});
I'm just lost after getting back the response on how to invoke a view within the template.
Since you are using ngRoute use $location.path() instead of $state.go(). The $location.path() method accepts a url specified in route configuration. E.g.:
$location.path('/found');
Say your controller is AppController, then the complete code will look something like:
angular.module('app', ['ngRoute'])
.controller('AppController', function ($location, $http) {
$scope.post = function (requestType, requestData) {
var uri = 'Search/' + requestType;
$http.post(uri, requestData)
.success(function (response) {
$scope.searchResult.ID = response.ID;
$scope.searchResult.Value = response.Value;
// how is the view/route loaded without a user click?
$location.path('/found');
}).error(function (error) {
// how is the view/route loaded without a user click?
$location.path('/notFound');
});
});
Refer https://docs.angularjs.org/api/ng/service/$location for api documentation of $location.path

setup 404 page using $routeProvider in angular js

Working on single page application everything is working fine but getting stuck when want to set 404 page when :username not found or any unexpected url will load in browser please check my code below
controller.js
var myApp = angular.module('assignment', ['ngRoute']);
myApp.service('userData', ['$http', function($http){
return{
userslist : function(){
return $http({'url' : 'js/data.json', 'method' : 'GET'}).then(function(response){
return response.data;
}, function(data){
console.log('some error')
})
}
}
}]);
myApp.config(function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'user-list.html',
controller: 'users'
}).
when('/:username', {
templateUrl: 'detail.html',
controller: 'userdetail'
}).
otherwise({
redirectTo: '/404.html' /*>>>>>>Here is the problem<<<<<<*/
});
});
myApp.controller('userdetail', ['$scope', '$routeParams', 'userData', function($scope, $routeParams, userData){
var selectedUser = $routeParams.username;
selectedUser = selectedUser.replace(/-/g, ' ');
userData.userslist().then(function(data){
$scope.items = [];
angular.forEach(data.data.bst_users, function(item){
if(item.name == selectedUser) {
$scope.user = item;
};
})
})
}])
myApp.controller('userdetail', ['$scope', '$routeParams', 'userData', function($scope, $routeParams, userData){
console.log($routeParams.username);
userData.find($routeParams.username, function(found){
$scope.user = found;
})
console.log(scope.user)
}])
/*******Filters*******/
myApp.filter('removeSpace',function() {
return function(input) {
if (input) {
return input.replace(/\s+/g, '-');
}
}
});
Since you declared /:username as a route, it can match anything after the /, meaning the 404 route isn't really doing anything and the username route in a sense is acting as your catch-all route. This is kind of a weird case, since you can't really define a regular 404 route. But what you could do is have a /404 route, then if /:username doesn't resolve to a user, redirect them to /404. That is the most efficient method I can come up with, but I guarantee there's a better way to do it.
#Jordan points out a definite issue.
I would recommend updating your user detail path to something like the following:
when('/user/:username', {
templateUrl: 'detail.html',
controller: 'userdetail'
})
Just so there is no confusion between /random_username and /unmatched_path.

AngularJS - Save data to $scope using routes?

i am just learning basics of angular and today it started to change my app using a factory to get data and implementing route provider ! So far everything works fine! But when I try to add data on another view and head back to my list view scope is reloaded again from factory and no added data shows up.
My approach won't work because each time change my view I will call my controller which reloads data from factory! What can I do to make my Add template will work and changes data everywhere else too.
Maybe somebody can give me a tip how to cope with this problem ?
script.js
var app = angular.module('printTrips', ['ngRoute']);
app.factory('tripFactory', function($http) {
return{
getTrips : function() {
return $http({
url: 'trips.json',
method: 'GET'
})
}
}
});
app.controller('TripController', function($scope, $filter, tripFactory) {
$scope.trips = [];
tripFactory.getTrips().success(function(data){
$scope.trips=data;
var orderBy = $filter('orderBy');
$scope.order = function(predicate, reverse) {
$scope.trips = orderBy($scope.trips, predicate, reverse)};
$scope.addTrip = function(){
$scope.trips.push({'Startdate':$scope.newdate, DAYS: [{"DATE":$scope.newdate,"IATA":$scope.newiata,"DUTY":$scope.newduty}]})
$scope.order('Startdate',false)
$scope.newdate = ''
$scope.newiata = ''
$scope.newduty = ''
}
$scope.deleteTrip = function(index){
$scope.trips.splice(index, 1);
}
});
});
view.js
app.config(function ($routeProvider){
$routeProvider
.when('/',
{
controller: 'TripController',
templateUrl: 'view1.html'
})
.when('/view1',
{
controller: 'TripController',
templateUrl: 'view1.html'
})
.when('/view2',
{
controller: 'TripController',
templateUrl: 'view2.html'
})
.when('/addtrip',
{
controller: 'TripController',
templateUrl: 'add_trip.html'
})
.otherwise({ redirectTo: 'View1.html'});
});
Here is my plunker
Thanks for your help
You should use Service instead of Factory.
Services are loaded each time they are called. Factory are just loaded once.
app.service('tripFactory', function($http) {
return{
getTrips : function() {
return $http({
url: 'trips.json',
method: 'GET'
})
}
}
});

Angular, problems with ngRoute code sequence

I am using ngRoute for reading the url parameters. The problem I have is that I can't get the ID while the code is running. However if try to call it as function I get values from url.
.controller('PageCtrl', function ($scope, $routeParams, Survey) {
$scope.survey = Survey.get({surveyId: $routeParams.id}); //doesn't work
this.add = function (pageId, pageIndex) {
console.log($routeParams.id); //works
};
$scope.Page = this;
}
Do you think there is the way of getting the url parameter while I am making the Survey.get() request ?
One way you could solve this would be to wait till the $routeChangeSuccess broadcast had been fired and then to initialise your $scope.survey.
i.e something like this
.controller('PageCtrl', function ($scope,$rootScope, $routeParams) {
$rootScope.$on('$routeChangeSuccess',function(){
$scope.survey = Survey.get({surveyId: $routeParams.id}); //doesn't work
});
this.add = function (pageId, pageIndex) {
console.log($routeParams.id); //works
};
$scope.Page = this;
}
Most likely your controller is called only once on the application startup. That's why your routeconfig isn't set yet and returns undefined. Are you sure you're specifying a controller to your view in your routeconfig?
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'partials/home.html',
controller: 'HomeCtrl'
}).
otherwise({
redirectTo: '/home'
});
}]);

AngularJS Pre-served $params variables for a controller defined inside of a route

Is it possible to pass your own variables in a defined route in AngularJS?
The reason why I'm doing this is because I have to data representations of the same page (one is a filtered view in terms of the JSON data) and all I need to do is give a boolean flag to the $params array to let the controller function know that this page is either filtered or non-filtered.
Something like this:
var Ctrl = function($scope, $params) {
if($params.filtered) {
//make sure that the ID is there and use a different URL for the JSON data
}
else {
//use the URL for JSON data that fetches all the data
}
};
Ctrl.$inject = ['$scope', '$routeParams'];
angular.modlule('App', []).config(['$routeProvider', function($routes) {
$routes.when('/full/page',{
templateURL : 'page.html',
controller : Ctrl
});
$routes.when('/full/page/with/:id',{
templateURL : 'page.html',
controller : Ctrl,
params : {
filtered : true
}
});
}]);
According to $routeProvider documentation, the route parameter of $routeProvider.when() has property resolve:
An optional map of dependencies which should be injected into the controller.
Something like this should work:
function Ctrl($scope, isFiltered) {
if(isFiltered) {
//make sure that the ID is there and use a different URL for the JSON data
}
else {
//use the URL for JSON data that fetches all the data
}
}
Ctrl.$inject = ['$scope', 'isFiltered'];
angular.modlule('App', []).config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/full/page',{
templateURL: 'page.html',
controller: Ctrl
});
$routeProvider.when('/full/page/with/:id',{
templateURL: 'page.html',
controller: Ctrl,
resolve: {
isFiltered: function() { return true; }
}
});
}]);
AFAIK it is not currently possible to specify additional parameters for a route. Having said this your use case could be easily covered by testing if :id is defined as part of $routeParams.
The thing is that AngularJS will match your routes either on '/full/page' or '/full/page/with/:id' so just by testing $routeParams for id presence in your controller:
if ($routeParams.id)
you would know in which case your are.
The alternative is to use different controllers for different routes.
mething like this must be work for filter:
function caseFilterCtrl($scope, $routeParams, $http) {
$http.get('./data/myDatas.json').success( function(data){
var arr = new Array();
for(var i=0; i < data.length; i++){
if(data[i].filter == $routeParams.id){
arr.push(data[i]); }
}
$scope.filtered= arr;
});
}
caseFilterCtrl.$inject = ['$scope', '$routeParams', '$http']; //for minified bug issue
and the routage :
angular.module('myFilterApp', []).
config(['$routeProvider', function($routeProvider){
$routeProvider.when('/filter/:id', {templateUrl: './view/partial/filter.html', controller: caseFilterCtrl});
$routeProvider.otherwise({redirectTo: '/filter/01'});
}
]);
You can get sneak params directly through $route.current.$$route.
function Ctrl($scope, $route) {
var filtered = $route.current.$$route.params.filtered;
}
angular.modlule('App', []).config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/full/page/with/:id',{
templateURL: 'page.html',
controller: Ctrl,
params : {
filtered : true
}
});
}]);
Although it work, I'd still prefer a resolve solution. params (or any name of your choice) could be overwritten by angularjs in future releases.

Resources