RouteParams in AngularJS - javascript

I am trying to pass a routeParam to a $http.post in my Angular controller, but I dont seem to be passing the value correctly. Here is what I have below. Am an not using the $routeParams correctly? When using $scope.event_id = $routeParams.eventId; the partial page renders correctly with Event: {{event_id}} or Event: 5 for example.
I need the $http.post to be php/getItem.php?itemID=5
The HTML passing the event_id:
{{event.event_name}}
The routeProvider:
var pvApp = angular.module('pvApp', ['ngRoute']);
// configure our routes
pvApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
.when('/:eventId', {
templateUrl : 'pages/event_detail.html',
controller : 'eventController'
});
});
The Controller:
pvApp.controller('eventController', function($scope, $http, $routeParams) {
// $scope.event_id = $routeParams.eventId;
$http.post("php/getItem.php?itemID="+$routeParams.eventId).success(function(data){
$scope.items = data;
});
});
The Partial Page:
<div class="container">
<div class="row">
<div class="col-lg-12">
<h2>Event: {{event_id}}</h2>
</div>
</div>
</div>

first check
console.log($routeParams.eventId);
is print the event_id on the console correctly.
Then
Note that your using a POST request but your url like GET request.
change the request like below and try,
$http({
url: 'php/getItem.php',
method: "POST",
data: { itemID : $routeParams.eventId },
}).succes...
OR
$http.post('php/getItem.php', { itemID:$routeParams.eventId }).success...
here you can get the data in Php as,
$data = json_decode(file_get_contents("php://input"));
$data->itemID // to access name
OR
$http({
url: 'php/getItem.php',
method: "POST",
data: { itemID : $routeParams.eventId },
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).succes...
In Php,
$name= $_POST['itemID'];
may be this post will helps you.

Related

How to get id from $http.get in angular.js

Hi I am a newbie and learning angular.js. I want to get data from this url which is actually an API (http://ba.dev/businesses/businesspage/36) but i dont know how can i Write this thing in my controller.js file. Given is my code please explain me how can I get the data from the business having id=36.
var reControllers = angular.module('reControllers',[]);
reControllers.controller('RecentController', ['$scope','$http' ,function($scope,$http){
$http.get('http://ba.dev/businesses/businesses').success(function(data){
$scope.business = data;
});
}]);
reControllers.controller('PageController', ['$scope','$http', '$routeParams' ,function($scope,$http,$routeParams){
$http.get('http://ba.dev/businesses/businesspage').success(function(data){
$scope.student = data;
$scope.whichItem = $routeParams.itemId;
});
}]);
Here is my app.js file
var myApp = angular.module('myApp',[
'ngRoute',
'reControllers'
]);
myApp.config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/main',{
templateUrl : 'partials/main.html',
controller : 'RecentController'
}).
when('/page/:itemId',{
templateUrl : 'partials/page.html',
controller : 'PageController'
}).
otherwise({
redirectTo: '/main'
});
}]);
You can get the id from URL using $routeParams
$http.get('http://ba.dev/businesses/businesspage/'+ $routeParams.itemId)
Thereafter add server side logic, get passed itemId from URL, perform needful operation for getting data from DB and return it back.
You should use then instead of success, because it is deprecated. So, your code should be: `
$http.get('http://ba.dev/businesses/businesses').then(function(data){
$scope.business = data;
}); }]);.....
From AngularJS documentation:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
More info about route params: AngularJS $routeParams

Angular not displaying $scope data with ng repeat passed in controller. No errors too

In this project, I am executing a query on click list item of ionic. I am getting the data from php json_encode. The data is getting displayed in the networks tab under response. Also, I have added $scope.doctorList = {}; and after that wrote this line $scope.doctorList = response which comes from success function. The data is getting displayed in console.log($scope.doctorList) as well.
Now when I try to display this data in angular, it does not show anything.
I have included it in ng-repeat as : ng-repeat = "doctors in doctorList"
The syntax seems to be correct as the same thing is working for another controller but here, I can't retrieve the data. The page goes blank and there is no error in console / netowrks tab.
I am using one controller for two html files. Please help
Here is the routes file
angular.module('app.routes', []).config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider.state('homeselect', {
url: '/home-select',
templateUrl: 'templates/homeselect.html',
controller: 'homeCtrl'
});
$stateProvider.state('home', {
url: '/home',
templateUrl: 'templates/home.html',
controller: 'homeCtrl'
});
});
Here is the controller
angular.module('app.controllers', []).controller('homeCtrl', function ($scope, $http, $ionicSideMenuDelegate, myServices, $window) {
$ionicSideMenuDelegate.toggleLeft();
$scope.loadDoc = function (type) {
$http({
url: "http://localhost/drmedic/retrieve_details_type.php",
method: "POST",
data: {
data: type
}
}).success(function (response) {
$scope.doctorList = {};
$scope.doctorList = response;
$window.location.href = '#/home-select';
});
};
$http({method: 'GET', url: 'http://localhost/drmedic/retrieve_details.php'}).success(function (data) {
$scope.contents = {};
$scope.contents = data;
});
});
Here is the html file code for ng-repeat
<ion-list ng-repeat="doctors in doctorList">
<ion-item>
<center>
{{doctors.name}}<br>
{{doctors.fees}}
</center>
</ion-item>
</ion-list>
You can use service.Open a file called service.js.After that this inject to app.js. I revised the code as follows:
Service.js:
angular.module('app.services', [])
.factory("AppService", function ($http) {
var AppService= {};
AppService.GetDetails = function (data) {
return $http({
url: "http://localhost/drmedic/retrieve_details_type.php",
method: "POST",
data: {
data: data
}
});
return AppService;
}
controller.js:
.controller('homeCtrl',function($scope,$http,$ionicSideMenuDelegate,myServices,$window,AppService) {
$ionicSideMenuDelegate.toggleLeft();
$scope.loadDoc = function(type){
AppService.GetDetails({type:type}).success(function (response) {
$scope.doctorList = {};
$scope.doctorList = response;
$window.location.href = '#/home-select';
})
.error(function (err) {
console.log(err);
});
}
});
ng-repeat iterates through a collection of items, create its own scope and renders it on UI. When I say collections, it should be an array.
https://docs.angularjs.org/api/ng/directive/ngRepeat
Please check the data-type for doctorList, which I believe is an array.
$scope.doctorList = [];
I hope this should solve the problem, if not please share the code I'll take a deep look into it.

Passing information previously retrieved to templateProvider in AngularJS

I'm using AngularJS 1.3 and UI-Router. I have an state in which i have a resolve and a templateProvider.
What i'm trying to accomplish is that the information retrieved from database in the resolve can be used by the templateProvider. Right now, I have to get the information twice, once from resolve and another from templateProvider, and that's annoying.
The code:
.state('articleurl', {
url: '/:articleUrl',
resolve: {
article: function ($http, $stateParams, $location) {
return $http({
method: 'GET',
url: '/articles/' + $stateParams.articleUrl
})
.then(function (article) {
return article;
}, function (error) {
$location.path('/404');
});
},
loggedin: checkLoggedin
},
templateProvider: ['$templateFactory', '$stateParams', '$http', function ($templateFactory, $stateParams, $http) {
return $http({
method: 'GET',
url: '/articles/' + $stateParams.articleUrl
}).then(function(article) {
if ( article.data.template )
return $templateFactory.fromUrl('articles/views/templates/' + article.data.template + '.html');
else
return $templateFactory.fromUrl('articles/views/templates/news.html');
});
}],
controller: 'ArticlesViewController'
})
As you can see, according to article's kind i load a different template in the templateProvider. Besides, i use the article's information in the controller which has been previously got in the state's resolve.
Is there any way to use in the templateProvider the information previously fetched in the resolve avoiding this way another call to database?
Right now, it is doing 2 calls to database per connection...
Thanks!
app.factory('article', function ($cacheFactory){
var articleCache = $cacheFactory('article');
return function (url) {
return articleCache.get(url) || articleCache.put(url, $http({
method: 'GET',
url: '/articles/' + url
})
);
};
});
Use it as article($stateParams.articleUrl).then(...) in both places, that will keep the things DRY. You may get better control over the cache (e.g. expiration) by replacing $cacheFactory with angular-cache.
$http own caching may be successfully used as well instead of explicit caching:
If there are multiple GET requests for the same URL that should be
cached using the same cache, but the cache is not populated yet, only
one request to the server will be made and the remaining requests will
be fulfilled using the response from the first request.
I think you can inject directly the resolved variables, so you could inject article in templateProvider:
.state('articleurl', {
url: '/:articleUrl',
resolve: {
article: function ($http, $stateParams, $location) {
return $http({
method: 'GET',
url: '/articles/' + $stateParams.articleUrl
})
.then(function (article) {
return article;
}, function (error) {
$location.path('/404');
});
},
loggedin: checkLoggedin
},
templateProvider: ['$templateFactory', '$stateParams', '$http', 'article', function ($templateFactory, $stateParams, $http, article) {
// Now here you can use article without the need to re-call it
}],
controller: 'ArticlesViewController'
})

cannot use a different controller with a view with ui-router AngularJS

I'm using ui-router for routing my angular app. I have the following route:
'use strict';
//Setting up route
angular.module('admins').config(['$stateProvider',
function($stateProvider) {
// Admins state routing
$stateProvider.
state('admin_home', {
url: '/admin',
templateUrl: 'modules/admins/views/list-admins.client.view.html'
}).
state('adduser', {
url: '/admin/create',
templateUrl: 'modules/admins/views/create-admin.client.view.html',
}).
state('viewAdmin', {
url: '/admins/:adminId',
templateUrl: 'modules/admins/views/view-admin.client.view.html'
}).
state('editAdmin', {
url: '/admins/:adminId/edit',
templateUrl: 'modules/admins/views/edit-admin.client.view.html'
});
}
]);
This is within my 'Admin' module, and that has its own controller (AdminsController).
However, I want to be able to create a new user from here, and the controller to do that is called 'AuthenticationController' and is elsewhere in the structure.
As far as I know, I should be able to put something like:
state('adduser', {
url: '/admin/create',
templateUrl: 'modules/admins/views/create-admin.client.view.html',
controller:'AuthenticationController'
})
and it should work.
However - I keep getting redirected back to the index page.
I suspect this may be because I'm using HTML5 and have this in my config also:
// use HTML 5
$locationProvider.html5Mode(true).hashPrefix('!');
//Sets the HTTP header type for the redirects
$httpProvider.defaults.headers.common = {
'Accept': 'application/json',
'Content-Type': 'application/json'
Can anyone help?
You should add :
$urlRouterProvider.otherwise("/home");
And declare your controller inside your state function (not in your view files) like that :
state('viewAdmin', {
url: '/admins/:adminId',
controller : AdminsController,
templateUrl: 'modules/admins/views/view-admin.client.view.html'
})
If it doesn't work, try to remove :
$locationProvider.html5Mode(true).hashPrefix('!');
//Sets the HTTP header type for the redirects
$httpProvider.defaults.headers.common = {
'Accept': 'application/json',
'Content-Type': 'application/json'
Let me know ;)

How to get json data in my case?

I am trying to use httml get to get the json
I have something like
.controller('testController', function($scope, $state, $http) {
$http({
url: "/json/test.json",
method: "GET",
}).success(function(data) {
$scope.testData = data;
console.log(data)
});
//outside of the $http scope but under the same controller, I have
//It shows undefined.
console.log($scope.testData)
})
I know we have to keep data our of the login codes so I don't want to modify the data inside the $http. Is there anyway to accomplish this? Thanks!
First, don't put this in a controller. Move it to a Service. That's what Services are designed for.
Second, the $http service is asynchronous. Your result only exists in the success callback, and your console.log will be called before the http request is finished. You need to assign it to a scope variable to use it outside of the callback, and expect it to be empty until the call back is complete.
http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app provides an example of an AngularJS authentication service, if that's what you're doing.
To go with your example:
.controller('testController', function($scope, $state, $http) {
$scope.testData = {};
$http({
url: "/json/test.json",
method: "GET",
}).success(function(data) {
$scope.testData = data;
$scope.logData();
});
$scope.logData = function() {
console.log($scope.testData);
}
});
This plnkr code is created in order to give your answer, yes you can have the $scope.testData outside the http request.
Have a look!!
var app = angular.module('plunker', []);
app.controller('testController', function($scope, $http) {
$http({
url: "test.json",
method: "GET",
}).success(function(data) {
$scope.testData = data;
alert(data);
callA();
});
function callA(){
alert($scope.testData);
}
});

Categories

Resources