I am trying to pass a routeParam to a $http.get in my Angular controller, but I am not getting data displayed.
Here is what I have below. Am I not using the $routeParams correctly?
link to JSON Data is http://enrolin.in/test/login.php?p=fetchone&&id=50
I need to pass the value of id dynamically.
Here is my angularJS code:
var app = angular
.module("Demo", ["ngRoute"])
.config(function ($routeProvider) {
$routeProvider
.when("/home", {
templateUrl: "templates/home.html",
controller: "homeController"
})
.when("/courses", {
templateUrl: "templates/courses.html",
controller: "coursesController"
})
.when("/students/:id", {
templateUrl: "templates/studentDetails.html",
controller: "studentDetailsController"
})
.otherwise({
redirectTo: "/home"
})
})
.controller("homeController", function ($scope) {
$scope.message = "Home Page";
})
.controller("coursesController", function ($scope) {
$scope.courses = ["C#", "VB.NET", "ASP.NET", "SQL Server"];
})
})
.controller("studentDetailsController", function ($scope, $http, $routeParams) {
$http({
url: "http://enrolin.in/test/login.php?p=fetchone&&id=",
method: "get",
params: { id: $routeParams.id }
}).then(function (response) {
$scope.stud = response.data;
})
})
Here is my partial page:
<h1>Student Details</h1>
<table style="border:1px solid black">
<tr>
<td>Id</td>
<td>{{stud.id}}</td>
</tr>
<tr>
<td>Name</td>
<td>{{stud.name}}</td>
</tr>
<tr>
<td>email</td>
<td>{{stud.username}}</td>
</tr>
</table>
<h4>Back to Students list</h4>
I checked using ng-inspector, When I load the page, It seems like data is being fetched but somehow not displayed. Please help.
Link to working application is http://enrolin.in/test/#/students/50
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;
})
});
How to add get request parameter from url to controller in angularjs
e.g. my request is http://localhost/abc-ang/#!/abc/8 and my controller code is
app.controller('AbcCtrl', function($scope,$http) {
$http.get("src/public/add/:id").then(function(response) {
$scope.abc = response.data;
});
});
I want to replace src/public/add/:id to src/public/add/8
how can I do that dynamically?
My routing configuration is
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/abc', {
templateUrl: "tpl/welcome.html"
})
.when('/abc/:wineId', {
templateUrl: 'tpl/abc-details.html',
controller: 'AbcDetailCtrl'
})
.otherwise({ redirectTo: '/abc' });
}]);
You can access URL params in your code with $routeParams:
From your comment your route is:
$routeProvider.when('/abc/:wineId', {
templateUrl: 'tpl/abc-details.html',
controller: 'AbcDetailCtrl'
});
So in your controller, you can get wineId value with:
app.controller('AbcCtrl', function($scope, $http, $routeParams) {
$http.get("src/public/add/" + $routeParams.wineId).then(function (response) {
$scope.abc = response.data;
});
});
Hi im new to angular and i have json data . SO when i click on Id obtained from json, it should route to different page. How should i do it
Head.html
</head>
<body ng-app="MyApp" ng-controller="MyController">
<table border="1" style="width:100%">
<tr >
<td href=#home>id</td>
<td>first_name</td>
<td>dateBirth</td>
<td>currentCountry</td>
</tr>
<tr ng-repeat="x in list">
<td>{{x.id}}</td>
<td>{{x.first_name}}</td>
<td>{{x.dateBirth}}</td>
<td>{{x.currentCountry}}</td>
</tr>
</table>
</body>
script.js
var app= angular.module("MyApp", []);
app.controller('MyController', function($scope,$http) {
$http({
method: "GET",
url: "http://192.168.1.1:8080/administrator/"
}).then(function mySucces(response) {
$scope.list = response.data;
console.log($scope.list)
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
my plunker http://plnkr.co/edit/Gpmsc7pb1gfWx3EgKk6s?p=preview
Any help is appreciated
There are various options to achieve what you are asking, using$routeProvider,$stateProvider and ng-click or ui-sref within that to achieve the navigation through id. I will go through a simple example using $stateProvider.
I will have 3 views to mock what you have provided:
header.html: which contains your ng-repeat to show the tabular data and whereby we have the click in the id to navigate.
first.html: if user clicks 1 in the id column, it is navigated to first.html
second.html: if user clicks 2 in the id column, it is navigated to second.html
Your JS:
var app = angular.module('nested', ['ui.router']);
app.config(function($stateProvider,$locationProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider.state('top', {
url: "",
templateUrl: "header.html",
controller: 'MyController'
})
.state('first', {
url: '/app/:id',
templateUrl: "first.html",
controller: 'FirstController'
})
.state('second', {
url: '/app/:id',
templateUrl: "second.html",
controller: 'SecondController'
})
});
app.controller('MyController', function($scope,$state) {
/*//commented this part so that you can work on it later.
$http({
method: "GET",
url: "http://192.168.1.134:8080/administrator/%20ApplicationList.json"
}).then(function mySucces(response) {
$scope.list = response.data;
console.log($scope.list)
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
*/
$scope.list = [{'id':1,'first_name':'alex','dateBirth':'18th march','currentCountry':'Nepal'},
{'id':2,'first_name':'rumba','dateBirth':'18th march','currentCountry':'USA'}
]
$scope.navigate = function(id){
if(id==1){
$state.go('first',{id:1});
}
else if(id==2){
$state.go('second',{id:2});
}
}
});
app.controller('FirstController', function($scope,$state) {
console.log(JSON.stringify($state.params));
$scope.params = $state.params;
});
app.controller('SecondController', function($scope,$state) {
console.log(JSON.stringify($state.params));
$scope.params = $state.params;
});
In this PLUNKER example, i have even provided how you pass params through controller:
http://plnkr.co/edit/n8p7ycV7k5rsn1f3bQcT?p=preview
You can add a ng-click attribute to your hyperlink tag like this
<td><a href="name.html" ng-click='displayFunc(x.id)'>{{x.id}}</a></td>
Now you can define this function in controller
$scope.displayFunc = function(id)
{
//Do something with id..
$location.path('/some route');
}
Don't forget to inject $location dependency in controller.
Below is the code which making some trouble
angular.module("cattle_feed_frontend", ['ngResource','ngRoute'])
.config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/',
{
controller: 'FeedController',
templateUrl: 'templates/FeedList.html'
}).
otherwise({
redirectTo: '/'
});
}])
.controller('FeedController', function($scope,feeds_factory) {
$scope.feeds = feeds_factory.allFeeds();
})
.factory('feeds_factory',['$http', function($http){
return {
allFeeds : function(){
$http.get("http://localhost:3000/feeds").then(function(response)
{
return response.data;
});
}
}
}])
In controller feeds_factory.allFeeds() making http call to a 3rd party . now when i see my console . It shows that my template is rendered first and then my http is made . Why? and issue due to this behavior is that my template is rendered in which i made the ng-repeat which makes nothing because $scope.feeds is set after its rendering , as follows
<tr ng-repeat="feed in feeds">
<td>
{{feed.ingredient}}
</td>
<td>
{{feed.cost_kg}}
</td>
</tr>
Because $routeProvider doesn't know your controller is going to make a http request, it doesn't know to wait. To tell it you use the resolve property of a route:
$routeProvider.
when('/',
{
controller: 'FeedController',
templateUrl: 'templates/FeedList.html',
resolve: {
feeds: function(feeds_factory) {
return feeds_factory.allFeeds();
}
}
}).
otherwise({
redirectTo: '/'
});
Then return the promise from feeds_factory:
factory('feeds_factory',['$http', function($http){
return {
allFeeds : function(){
return $http.get("http://localhost:3000/feeds").then(function(response) {
return response.data;
});
}
}
}])
Then inject into the controller:
controller('FeedController', function($scope, feeds) {
$scope.feeds = feeds;
})
Most likely you need to change your code to this:
.controller('FeedController', function($scope,feeds_factory) {
feeds_factory.allFeeds()
.then(function(feeds) {
$scope.feeds = feeds;
});
})
So, I've been trying to set up an app using Yeoman's official angular gen and this hapijs generator for the backend. Now, so far on the backend I've only got the home route serving the index.html as you can see here
server.route({
method: "GET",
path: "/{param*}",
handler: {
directory: {
path: ["../../client/app", "../../client/bower_components"]
}
},
config: {
auth: false
}
});
next();
};
exports.register.attributes = {
name: 'index'
};
The thing is that worked until I tried to add a new service, controller and view to the angular app, when I did so the views stopped rendering.
Heres the service:
angular.module('graphMeDota2App', [])
.service('MatchesService', ['$httpq', 'config', function ($httpq, config) {
// AngularJS will instantiate a singleton by calling "new" on this function
return {
GetAllMatches: function(){
return $httpq.get(config.steamApiBaseUrl + 'IDOTA2Match_570/GetMatchHistory/v001/?key' + config.steamApiKey + '&accountId' + config.steamAccountId + '&matches_requested=5');
}
};
}]);
Heres the controller:
angular.module('graphMeDota2App')
.controller('MatchesCtrl', ['MatchesService', function ($scope, MatchesService) {
$scope.matches = {};
$scope.getMatches = function(){
MatchesService.GetAllMatches().done(function(response){
$scope.matches = response.data;
});
};
$scope.getHeroPlayed = function(match){
console.log(match);
return 'asdfasdf';
};
}]);
Heres the view:
<div class="jumbotron">
<table>
<tr>
<th>Number</th>
<th>Match Id</th>
</tr>
<tr ng-repeat="match in matches">
<th>{{$index}}</th>
<th>{{match.match_id}}</th>
</tr>
</table>
</div>
And here's my app.js:
angular
.module('graphMeDota2App', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.when('/matches', {
templateUrl: 'views/matches.html',
controller: 'MatchesCtrl'
})
.otherwise({
redirectTo: '/'
});
});
And finally, this is what I get: .
There are no javascript errors, no server sider errors and the views were rendering perfectly before I added my controller/service (both added with the yeoman command line generator).
So, following what Byron Sommardahl said found out the problem was when I was creating my service, specifically this line:
angular.module('graphMeDota2App', [])
.service('MatchesService', ['$httpq', 'config', function ($httpq, config) {
Only thing I did was remove the first "[]" in the first line, then it started working. Any thoughts on why that happened?
angular.module('graphMeDota2App')
.service('MatchesService', ['$http', 'config', function ($http, config) {