I'm sure this problem has a simple answer, but, for once, I'm stumped. I want to have a URL like http://www.website.com/item/1234 display information about an item with id '1234'. I have an Angular controller set up to query for it and render its data. This works, provided the id is valid. However, I can't figure out how to pass the id, in the first place. I have tried lots of routing examples, but none of them work when I try to implement them, so I'm missing something.
Here is the server route in Express/Node:
router.get('/item/:id', function(req, res, next) {
res.render('item');
});
Here is the Angular route:
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.when('/item/:id', {
controller: 'ShowItem'
});
$locationProvider.html5Mode(true);
}]);
The controller is trying to access 'id' here:
app.controller('ShowItem', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
console.log($routeParams.id);
var itemID = $routeParams.id;
$http({
method: 'GET',
url: '/queries/get_item',
params: {
itemID: itemID
}
}).success(function(data, status, headers, config) {
if (data) {
$scope.itemValue = data;
$scope.type = $scope.itemValue['SaleType'];
$scope.setAllBidHistory(false);
if (Date.getStamp() >= $scope.itemValue['ExpirationTimeStamp']) {
$scope.expired = true;
} else {
$scope.expired = false;
}
}
}).error(function(data, status, headers, config) {
alert('There was an error fetching item: '+status);
});
...
}]);
The page renders, but $routeParams.id is undefined.
Related
I want to add some delay in angularjs. So that it can fetch data from api. Because my api is heavy. I am calling this function. Basically i want some delay to load page so that my api work properly. I tried some time my data pull immediate some time i am getting error. When i refresh my page it work fine.
Help to put $timeout function in this angularjs
// Geting test stuff
$scope.teststuff = function () {
$scope.loading = true;
$http.get(settings.WebApiBaseUrl + 'Api/testing')
.success(function (data) {
$scope.mydata = data;
$scope.loading = false;
}).error(function (data, status, headers, config) {
alert("Error " + status )
$scope.loading = false;
})
}
Updated:
This problem can easily be solved by using resolve property of $routerProvider. Please use this config. So here the route /ed will not load until the resolve is completed, meaning the http request must return a value, only after that the page will load.
app.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {
var settings.WebApiBaseUrl = "some url you want to use";
$routeProvider.when("/al", { templateUrl: "Views/test.html", controller: "testCtrl" })
.when("/ed", {
templateUrl: "Views/test2.html",
controller: "test2Ctrl",
resolve: {
initialize: function($http, $sessionStorage){
$http.get('api/ApiKey/' + $sessionStorage.user)
.success(function (myKey) {
return $http.get(settings.WebApiBaseUrl + 'Api/test1', { headers: { 'X-ApiKey': myKey } })
.success(function (data) {
return data;
}).error(function (data, status, headers, config) {
alert("error" + status);
});
}).error(function (data, status, headers, config) {
alert("error" + status);
});
}
}
})
.otherwise({
redirectTo: '/al'
});
}]);
Now in the controller you need to do.
app.controller( 'test2Ctrl', function ( $scope, initialize ) {
$scope.loading=false;
$scope.test1=initialize;
$scope.loading=true;
});
Old Answer:
so you have a http request which is a promise and will wait until the data is received and from your example I can see you are implementing a loading screen kind of thing until the http request is completed.
To ensure the bulky http request doesn't time out you can use.
angular.module('MyApp', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.timeout = 5000;
}]);
While the page waits for the http request to complete you can use the scope variable($scope.loading = true;) to activate a loading spinner library to mask your page. Checkout angular loading overlay or some other code to do this.
Reference:
http timeout
Hi friends, I want to read parameter from current URL of the page in
angularJS. My page URL is
'http://localhost:9999/ADMIN_APP_0.1/Security_Question.jsp?user_id=1'.I
want to read this user_id in Security_Question.jsp
I googled and I got something Route in angular but my code style and its style is quite different.And I don't know about route.
Forgot password is jsp page which is calling security question page
Forgot_Password.jsp
var app = angular.module('formSubmit', []);
app.controller('forgotController',[ '$scope', '$http', function($scope, $http) {
$scope.listOfSecurityQues=[];
$scope.getAvailableUser = function() {
var loginId= {
"user_login" :$scope.loginid
};
window.alert(" login ::::"+loginId);
var response = $http.post('loginController/loginidAvailable', loginId);
response.success(function(data, status, headers, config) {
window.location="./SecurityQuestion.jsp?user_id="+data;
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " +data+" "+status);
});
//Empty list data after process
$scope.list = [];
}; // end of getAvailableUser
Security_Question .jsp
var app = angular.module('formSubmit', []);
app.controller('forgotController', ['$scope','$http',function($scope,
$http) {
$scope.listOfUserSecurityQues = [];
$scope.getUserQuestions = function()
{
//here i want that URL user_id
var response = $http({method : 'GET',
url : "loginController/getUserQuestions"+user_id
});
response.success(function(data, status, headers, config) {
angular.forEach(data, function(value, key) {
$scope.listOfUserSecurityQues.push(value);
})
})
response.error(function(data, status, headers, config) {
})
};//end of getQuestions()
} ]);
by using $location we can read parameter of url.
app.controller('Controller', ['$scope','$http','$location',
function($scope, $http,$location)
{
$scope.Id=0;
$scope.getUserQuestions=function(){
var url = $location.search();
angular.forEach(url,function(value,key){
$scope.Id=parseInt(value);
window.alert($scope.Id);
}) }
I'm trying to get ui-router to work and I'm getting pretty close. Well I got it working, but I can't combine it with my controller, then I'm getting errors.
I'm getting this error in the console
Error: [ng:areq] Argument 'searchCtrl' is not a function, got undefined
searchCtrl.js
var myApp = angular.module('myApp')
.controller('searchCtrl', [
'$scope', '$http', function($scope, $http) {
$scope.search = function() {
var base = 'http://api.themoviedb.org/3';
var service = '/search/movie';
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
var search = $scope.searchquery
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + service + '?api_key=' + apiKey + search + '&callback=' + callback;
$http.jsonp(url,{ cache: true}).
success(function (data, status, headers, config) {
if (status == 200) {
$scope.movieList = data.results;
console.log($scope.movieList)
} else {
console.error('Error happened while getting the movie list.')
}
}).
error(function (data, status, headers, config) {
console.error('Error happened while getting the movie list.')
});
}
}
]);
My searchModule.js
var app = angular.module('movieseat', ['ui.router']).config([
'$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/state1');
return $stateProvider.state('state1', {
url: '/state1',
templateUrl: 'assets/angular-app/templates/state1.html'
});
}
]);
And my app.js.coffee
#app = angular.module('movieseat', []);
#myApp = angular.module('myApp',[]);
# for compatibility with Rails CSRF protection
#app.config([
'$httpProvider', ($httpProvider)->
$httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content')
])
#app.run(->
console.log 'angular app running'
)
This might be the same question and I've tried adding another module to my app.js.coffee but it's not working.
Does anyone have a tip?
Change first two module declaration line of your app.js.coffee like below.
#myApp = angular.module('myApp',[]);
#app = angular.module('movieseat', ['myApp','ui.router']);
and then in searchModule.js
angular.module('movieseat').config([
'$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/state1');
return $stateProvider.state('state1', {
url: '/state1',
templateUrl: 'assets/angular-app/templates/state1.html'
});
}
]);
REASON : Here you are basically overriding the module you previously created insted you just need to use that already declared module.
If you are doing with single module then
#app = angular.module('movieseat', ['myApp','ui.router']);
# for compatibility with Rails CSRF protection
#app.config([
'$httpProvider', ($httpProvider)->
$httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content')
])
#app.run(->
console.log 'angular app running'
)
and
angular.module('movieseat').config([
'$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/state1');
return $stateProvider.state('state1', {
url: '/state1',
templateUrl: 'assets/angular-app/templates/state1.html'
});
}
]);
and your controller looks like
angular.module('movieseat')
.controller('searchCtrl', [
'$scope', '$http', function($scope, $http) {
$scope.search = function() {
var base = 'http://api.themoviedb.org/3';
var service = '/search/movie';
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
var search = $scope.searchquery
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + service + '?api_key=' + apiKey + search + '&callback=' + callback;
$http.jsonp(url,{ cache: true}).
success(function (data, status, headers, config) {
if (status == 200) {
$scope.movieList = data.results;
console.log($scope.movieList)
} else {
console.error('Error happened while getting the movie list.')
}
}).
error(function (data, status, headers, config) {
console.error('Error happened while getting the movie list.')
});
}
}
]);
I'm new on angular js and i'm trying to get parameters from the url i've read some documentation about routeparams but i'm getting it empty.
here is my code
var study = angular.module('study', ['ngRoute'], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
study.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('edit/:id', {
controller: 'EditController'
});
}]).controller('EditController',
function($scope, $http, $compile, $rootScope, $routeParams, $route ) {
$scope.item = null;
console.log($routeParams);
console.log($rootScope);
var id = $routeParams.$id;
$scope.onLoad = $http({
method: 'get',
url: 'item',
data: {id:id}
}).success(function(data, status, headers, config) {
$scope.item = data;
}).error(function(data, status, headers, config) {
alert(status);
});
});
I've come to this problem were my view loads before $scope params are assigned and this is caused by $http service call taking some time before response is achived.
This leaves me with dropdown boxes being unsync with url params on page reload...
Is there anyway to reload these $scope params or wait til they get values before rendering the view? I would like the easiest solution to this as Im yet farily new to angularjs.
Just give me a hint if more info is needed!
Here's some of the code...
Route
angular.module('app', ['ngRoute', 'app.controller', 'app.service', 'app.filter'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/order/:id', {
templateUrl: '../../App_AngularJs/partials/specificOrder.htm',
controller: 'orderController',
reloadOnSearch: true
})
.when('/orderitem/:id', {
templateUrl: '../../App_AngularJs/partials/orderItem/orderItem.htm',
controller: 'orderItemController',
reloadOnSearch: true
})
.when('/', {
templateUrl: '../../App_AngularJs/partials/searchOrder.htm',
controller: 'ordersController',
reloadOnSearch: false
//Use some resolve here!? How!?
});
}
Controller
var orderContrl = angular.module('app.controller', ['angularTreeview', 'ui.bootstrap'])
.controller('ordersController', [
'$scope', '$routeParams', '$location', '$filter', '$modal', '$log', 'orderService',
function ($scope, $routeParams, $location, $filter, $modal, $log, orderService) {
init();
function init() {
$scope.searchtext = $routeParams.search || '';
$scope.page = $routeParams.page || 1;
$scope.take = $routeParams.take || 10;
$scope.status = $routeParams.status || -1;
$scope.group = $routeParams.group || -1;
$scope.type = $routeParams.type || -1;
$scope.category = $routeParams.category || -1;
$scope.selectedOrganisation = "Knoc LK";
getOrders(true);
getFilters(true);
}
function getFilters(reloadPage) {
orderService.queryOrderAllDropdown()
.then(function (response) {
$scope.orderGroup = response.OrderGroups;
$scope.orderStatus = response.OrderStatus;
$scope.orderType = response.OrderTypes;
$scope.orderPackageCategory = response.ProductPackageCategories;
$scope.orderAllCategory = response.ProductItemCategories;
//Sets type and shows different categories depending on type chosen
getCategory();
//Trying to reassign the values but still nothing...
if (reloadPage) {
angular.forEach($scope.orderStatus, function (value) {
if ($routeParams.status == value.ID)
$scope.status = value.ID;
});
//Trying to reassign the values but still nothing...
$scope.group = $scope.group;
}
},
function (errorMessage) {
$scope.error = errorMessage;
});
}
Service
angular.module('app.service', [])
.service('orderService', ['$http', '$q', function ($http, $q) {
this.queryOrderAllDropdown = function () {
var deferred = $q.defer();
$http({
type: 'GET',
url: 'GenericHandlers/HttpOrderService.ashx',
method: 'GetOrderAllDropdown',
headers: { 'Content-Type': 'text/plain' }
}).success(function (data) {
deferred.resolve(data);
}).error(function () {
deferred.reject("An error occured while fetching data");
});
return deferred.promise;
},
You need to use a Resolver to fetch the data from the backend. Adding a "resolve" to the $routeProvider will fetch the data before the controller takes control. Check out this blog post for a similar example.