I'm new to json and can't get data from request correct.
I haven't got any problems with getDrivers(), but when I try to get data from getDriverRaces($scope.id) I get nothing.
I've tried to do it manualy: http://ergast.com/api/f1/2015/drivers/hamilton/results.json?callback=JSON_CALLBACK
and result was -
angular.module('F1FeederApp.controllers', []).
controller('driversController', function ($scope, ergastAPIservice) {
$scope.nameFilter = null;
$scope.driversList = [];
$scope.searchFilter = function (driver) {
var re = new RegExp($scope.nameFilter, 'i');
return !$scope.nameFilter || re.test(driver.Driver.givenName) || re.test(driver.Driver.familyName);
};
ergastAPIservice.getDrivers().success(function (response) {
$scope.driversList = response.MRData.StandingsTable.StandingsLists[0].DriverStandings;
});
}).
controller('driverController', function ($scope, $routeParams, ergastAPIservice) {
$scope.id = $routeParams.id;
$scope.races = [];
$scope.driver = null;
ergastAPIservice.getDriverRaces($scope.id).success(function (response) {
$scope.races = response.MRData.RaceTable.Races;
});
});
<div class="main-content">
<table class="result-table">
<thead>
<tr><th colspan="5">Formula 1 2015 Results</th></tr>
</thead>
<tbody>
<tr>
<td>Round</td>
<td>Grand Prix</td>
<td>Team</td>
<td>Grid</td>
<td>Race</td>
</tr>
<tr ng-repeat="race in races">
<td>{{race.round}}</td>
<td>{{race.raceName}}</td>
<td>{{race.Results[0].Constructor.name}}</td>
<td>{{race.Results[0].grid}}</td>
<td>{{race.Results[0].position}}</td>
</tr>
</tbody>
</table>
</div>
angular.module('F1FeederApp.services', [])
.factory('ergastAPIservice', function ($http) {
var ergastAPI = {};
ergastAPI.getDrivers = function () {
return $http({
method: 'JSONP',
url: 'http://ergast.com/api/f1/2015/driverStandings.json?callback=JSON_CALLBACK'
});
}
ergastAPI.getDriverRaces = function (id) {
return $http({
method: 'JSONP',
url: 'http://ergast.com/api/f1/2015/drivers/' + id + '/results.json?callback=JSON_CALLBACK'
});
}
return ergastAPI;
});
Any help would appreciate.
The problem is that because of carelessness I entered same controller twice, because of common name.
.
config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when("/drivers", { templateUrl: "partials/drivers.cshtml", controller: "driversController" }).
when("/drivers/:id", { templateUrl: "partials/driver.cshtml", controller: "driverController" }).
otherwise({ redirectTo: "/drivers" });
}]);
I think your problem is how you are trying to get at the data in the success functions.
This
ergastAPIservice.getDriverRaces($scope.id).success(function (response) {
$scope.races = response.MRData.RaceTable.Races;
});
should be this (data returned from a $http call is in response.data)
ergastAPIservice.getDriverRaces($scope.id).success(function (response) {
$scope.races = response.data.MRData.RaceTable.Races;
});
The response object has the following properties (see documentation here near top)
data - your response should be in here
status
headers
config
statusText
You are trying to access property response.MRData which will never exist but response.data.MRData should
Related
books.html
<div ng-controller="BookController">
<table datatable="ng" class="row-border hover" ng-table="tableParams">
<thead>
<tr>
<th>BookID</th>
<th>BookName</th>
<th>Author</th>
<th>ISBNCode</th>
<th>NoOfBooks</th>
<th>PublishDate</th>
<th>NoOfBooksIssued</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="book in books">
<td>{{book.BookId}}</td>
<td>{{book.BookName}}</td>
<td>{{book.Author}}</td>
<td>{{book.ISBNCode}}</td>
<td>{{book.NoOfBooks}}</td>
<td>{{book.PublishDate}}</td>
<td>{{book.NoOfBooksIssued}}</td>
<td><p data-placement="top" data-toggle="tooltip" title="Edit"><button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit"><span class="glyphicon glyphicon-pencil"></span></button></p></td>
<td><p data-placement="top" data-toggle="tooltip" title="Delete"><button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete"><span class="glyphicon glyphicon-trash"></span></button></p></td>
</tr>
</table>
</div>
Bookcontroller.js
"use strict";
(function () {
angular.module("Bookapp")
.controller("BookController", ["$scope", "BookService",
function ($scope, bookService) {
bookService.getRequest()
.then(function (response) {
$scope.books = JSON.parse(response);
});
}]);
})();
AddBookController.js
"use strict";
(function () {
angular.module('Bookapp')
.controller('AddBookController', ["$scope", "BookService",
function ($scope, bookService) {
$scope.save = function (item) {
bookService.postRequest(item)
.then(function () {
location.path("books");
});
}
}]);
})();
Both the js files are 2 different custom files which are included in the master page. I have also written BookService.js. Which is as follows:
"use strict";
(function () {
angular.module("Bookapp")
.factory("BookService", ["$http", "$q", function ($http, $q) {
var baseURL = "http://localhost:27136/api/book";
var getRequest = function (query) {
var deferred = $q.defer();
$http({
url: baseURL,
method: "GET"
})
.success(function (result) {
deferred.resolve(result);
})
.error(function (result, status) {
deferred.reject(status);
});
return deferred.promise;
};
var getByIdRequest = function (id) {
var deferred = $q.defer();
$http({
url: baseURL + "/" + id,
method: "GET"
})
.success(function (result) {
deferred.resolve(result);
})
.error(function (result, status) {
deferred.reject(status);
});
return deferred.promise;
};
var postRequest = function (data) {
var deferred = $q.defer();
$http({
url: baseURL,
method: "POST",
data: JSON.stringify(data)
})
.success(function (result) {
deferred.resolve(result);
})
.error(function (result, status) {
deferred.reject(status);
});
return deferred.promise;
};
var updateRequest = function (data, id) {
var deferred = $q.defer();
$http({
url: baseURL + "/" + id,
method: "PUT",
data: JSON.stringify(data)
})
.success(function (result) {
deferred.resolve(result);
})
.error(function (result, status) {
deferred.reject(status);
});
return deferred.promise;
};
var deleteRequest = function (id) {
var deferred = $q.defer();
$http({
url: baseURL + "/" + id,
method: "DELETE"
})
.success(function (result) {
deferred.resolve(result);
})
.error(function (result, status) {
deferred.reject(status);
});
return deferred.promise;
};
return {
getRequest: getRequest,
getByIdRequest: getByIdRequest,
postRequest: postRequest,
updateRequest: updateRequest,
deleteRequest: deleteRequest
};
}]);
})()
My problem is when I click on the add button below my table the details of the book that i have entered must update in the table immediately which is not happening in my case. I have 2 different controllers one is BookController which will get all the books details from db using a service method and display in the table. The other one is AddBookController which will add the new book details to the table.In AddBookController itself i have written code to get the data after posting it to db. But i am not able to refresh the table with new data.Please help me. Thank you so Much in advance!
First of all you have a code smell in your service because you don't need to use $q service for retrieving a promise from $http.
$http always return a promise itself!
so you can simplify all your functions like this:
var getRequest = function (query) {
return $http({
url: baseURL,
method: "GET"
});
};
For your question
Have you try debugging the bookService.getRequest() request?
Try putting a console.log in your book controller and see if it's called after the add.
Maybe you need to trigger the get request after the add.
"use strict";
(function () {
angular.module('Bookapp')
.controller('AddBookController', ["$scope", "BookService",
function ($scope, bookService) {
$scope.save = function (item) {
console.log(item);
bookService.postRequest(item)
.then(function () {
bookService.getRequest()
.then(function (response) {
$scope.books = JSON.parse(response);
});
});
}
}]);
})();
I'm trying to write down a Controller that pass a var to a Factory in Angularjs.. The following code return (in console) the values, but I'm not been able to load that into my html page.
Just to record, yes, I'm starting in angularjs.
app.js
var myApp = angular.module('myApp',[]);
myApp.factory('eventData', function ($http, $q) {
delete $http.defaults.headers.common['X-Requested-With'];
return {
getEvent: function (id) {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'page' + id
}).
success(function (data, status, headers, config) {
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
};
});
myApp.controller('AngularJSCtrl',
function FeederController($scope, eventData) {
$scope.data = [];
for (var i = 0; i < 10; i++) {
eventData.getEvent(i).then(
function (data) {
$scope.data = data;
console.log($scope.data);
},
function (statusCode) {
console.log(statusCode)
});
}
}
);
page.html
<div ng-controller="AngularJSCtrl">
<div ng-repeat="patient in patients">
<businesscard>{{patient.name}}</businesscard>
</div>
</div>
Problem solved. I've searched for a while until get this right.
Thanks for #Claies and Brad Barrow for the tips :)
app.js
var myApp = angular.module('myApp',[]);
myApp.factory('patientsData', function ($http) {
delete $http.defaults.headers.common['X-Requested-With'];
return {
getPatients: function () {
return $http({
url: 'http://localhost/ucamradio/php/tst.php?campusId=1',
method: 'GET'
})
}
}
});
myApp.controller('AngularJSCtrl', function($scope, patientsData){
$scope.patients = [];
var handleSuccess = function(data, status) {
//$scope.patients = data;
$scope.patients.push(data);
console.log($scope.patients);
};
patientsData.getPatients().success(handleSuccess);
});
page.html
<div ng-controller="AngularJSCtrl">
<div ng-repeat="patient in patients">
<businesscard>{{patient.name}}</businesscard>
</div>
<!--
<div ng-repeat="patient in patients ">
<businesscard>{{patient.id}}</businesscard>
</div> -->
</div>
I've tried different variations of $apply() and $digest() to no avail.
The binding should update once the courier is no longer null with the name of the courier, however nothing is happening. I've been able to log the name of the courier when they are assigned, however the dom element is not updating. I'm using jade and compiling to html without any issues elsewhere in the application. I'm also calling the refreshDelivery function immediately prior to rendering the view shown below, which is working correctly.
app.js:
var storeController = require('./controllers/controller');
var storeApp = angular.module('AngularStore', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/store', {
templateUrl: 'views/store.html',
controller: storeController }).
when('/products/:productSku', {
templateUrl: 'views/product.html',
controller: storeController }).
when('/cart', {
templateUrl: 'views/shoppingCart.html',
controller: storeController }).
when('/delivery', {
templateUrl: 'views/delivery.html',
controller: storeController }).
otherwise({
redirectTo: '/store' });
}])
.controller('storeController', storeController);
controller.js:
function storeController($scope, $routeParams, $http, $interval, DataService) {
// get store and cart from service
$scope.store = DataService.store;
$scope.cart = DataService.cart;
$scope.mapInit = DataService.mapInit;
// use routing to pick the selected product
if ($routeParams.productSku != null) {
$scope.product = $scope.store.getProduct($routeParams.productSku);
}
// var locationOptions = {
// enableHighAccuracy: true,
// timeout: 5000,
// maximumAge: 0
// }
// navigator.geolocation.getCurrentPosition(function(pos){
// var mapOptions = {
// center: { lat: pos.coords.latitude, lng: pos.coords.longitude},
// zoom: 13
// };
// var map = new google.maps.Map(document.getElementById('map'),
// mapOptions);
// });
$scope.search = function(query){
var responseObject;
console.log('in search');
$http({
url:'/apiCall',
data: {data: '/products?keyword=' + query + '&latlong=36.125962,-115.211263'},
method: 'POST'
})
.then(function(response){
responseObject = response.data.data;
responseObject.forEach(function(data){
var productData = {
sku: data.Id.SkuPartNumber,
productName: data.Description.Name,
desc: data.Description.BrandName,
price: data.Price.DisplayPrice,
url: data.Description.ImageURL,
storeNumber: data.StoreNumber
}
var temp = new product(productData)
$scope.store.addProduct(temp)
});
});
}
$scope.getDeliveryQuote = function(){
var responseObject;
$scope.quoted = false;
var storeNumber = $scope.cart.items[0].storeNumber
console.log($scope.cart.items[0].storeNumber);
var url = '/delivery_quote?drop_off_latlong=36.125962,-115.211263&pickup_store_number='.concat(storeNumber);
$http({
url: '/apiCall/',
data: {data: url},
method: 'POST'
})
.then(function(response){
$scope.quoted = true;
console.log(response.data.id);
$scope.quote = response.data.fee;
$scope.quoteId = response.data.id
})
}
$scope.submitOrder = function(){
var url = '/submit_delivery?drop_off_latlong=36.125962,-115.211263&pickup_store_number=0001709&manifest=puppies&phone_number=555-555-5555"e_id=' + $scope.quoteId + '&customer_name=Arnold';
$http({
url: '/apiCall/',
data: {data: url},
method: 'POST'
})
.then(function(response){
console.log(response);
$scope.deliveryId = response.data.id;
$scope.refreshDelivery();
window.location.href='/#/delivery';
})
}
$scope.refreshDelivery = function() {
var url = '/update?delivery_id='.concat($scope.deliveryId);
var promise = $interval(function(){
$http({
url: '/apiCall/',
data: {data: url},
method: 'POST'
})
.then(function(resp) {
$scope.update = resp.data;
if (resp.data.courier){
$scope.update.courier = resp.data.courier;
console.log($scope.update.courier.name);//outputs correct name
$scope.$apply();
}
//stops when complete
if ($scope.update.complete){
$interval.cancel(promise);
}
})
}, 5000 );
}
}
module.exports = storeController;
Jade before compiling to HTML:
Partial:
p.text-info {{update.courier.name}} is on their way!
Default:
html(ng-app='AngularStore')
head
// includes for jquery, angular, and bootstrap
script(src="https://maps.googleapis.com/maps/api/js?sensor=false")
script(src='bower_components/jquery/dist/jquery.min.js')
script(rel='stylesheet' href='bower_components/bootstrap/dist/css/bootstrap.min.css')
script(src='bower_components/angular/angular.js')
script(src='bower_components/angular-route/angular-route.js')
// includes for the Angular Store app
script(src='/js/main.js')
script(src='/js/bundle.js')
link(href='/styles/main.css', rel='stylesheet', type='text/css')
|
body
.container-fluid
.row-fluid
.span10.offset1
h1.well
a(href='default.html')
| Angular Store
div(ng-view='')
I found a way around the $scope issue by creating a separate controller to handle updates.
app:
var storeController = require('./controllers/storeController'),
deliveryController = require('./controllers/deliveryController');
var storeApp = angular.module('AngularStore', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/store', {
templateUrl: 'views/store.html',
controller: storeController }).
when('/products/:productSku', {
templateUrl: 'views/product.html',
controller: storeController }).
when('/cart', {
templateUrl: 'views/shoppingCart.html',
controller: storeController }).
when('/delivery/:id', {
templateUrl: 'views/delivery.html',
controller: deliveryController }).
otherwise({
redirectTo: '/store' });
}])
.controller('storeController', storeController);
new deliveryController
function deliveryController($scope, $routeParams, $http, $interval) {
console.log($routeParams);
var refreshDelivery = function(id) {
var url = '/update?delivery_id='.concat(id);
var promise = $interval(function(){
$http({
url: '/apiCall/',
data: {data: url},
method: 'POST'
})
.then(function(resp) {
$scope.update = resp.data;
if (resp.data.courier){
$scope.update.courier = resp.data.courier;
console.log($scope.update.courier.name);//outputs correct name
}
//stops when complete
if ($scope.update.complete){
$interval.cancel(promise);
}
})
}, 5000 );
}
refreshDelivery($routeParams.id);
}
module.exports = deliveryController;
I'm a beginner in angularjs. What I’m trying to do is from view to pass params to the controller, which to return at its side, different results from factory. The problem is that when it goes to call metod with params from some view the result is an infinity loop.
I've the following config:
app.config(function($locationProvider, $stateProvider, $urlRouterProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
}).hashPrefix('!');
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'templates/home.html',
controller: 'StoreController as store'
})
})
My Factory is:
app.factory('BookFactory', function($http, $q){
var service = {};
var baseUrl = 'http://someAPI/ ';
var _query = '';
var _finalUrl = '';
var makeUrl = function() {
_finalUrl = baseUrl + _query;
}
service.setQuery = function(query) {
_query = query;
}
service.getQuery = function() {
return _query;
}
service.callBooks = function() {
makeUrl();
var deffered = $q.defer();
$http({
url: _finalUrl,
method: "GET"
}).success(function(data, status, headers, config) {
deffered.resolve(data);
}).error(function(data, status, headers, config) {
deffered.reject
})
return deffered.promise;
}
return service;
});
And the controller is:
app.controller('StoreController', ['BookFactory',function(BookFactory) {
var store = this;
store.products = [];
this.submitQuery = function(param) {
BookFactory.setQuery(param);
BookFactory.callBooks()
.then(function(data){
store.products = data;
}, function (data) {
alert(data);
});
}
}]);
Home.html when I call the method as follows:
ng-repeat="product in store.submitQuery('php')"
This causes an infinite loop and I can’t understand why, but if I change a bit the controller in the following way:
app.controller('StoreController', ['BookFactory',function(BookFactory) {
var store = this;
store.products = [];
this.submitQuery = function(param) {
BookFactory.setQuery(param);
BookFactory.callBooks()
.then(function(data){
store.products = data;
}, function (data) {
alert(data);
});
}
this.submitQuery('php');
}]);
The difference is that in the controller submitQuery is called
Than in home.html:
ng-repeat="product in store"
Things are going well but I wish thought the през view to pass different parameters.
Thanks in advance.
ng-repeat="product in store.submitQuery('php')"
of course this will make infinite loop ,cause when you make request,ng-repeat is redrawing and invoke same query over and over,
in order to pass diffrent param for query you can bind any variable to view
html
<input ng-model="queryParam" />
controller
app.controller('StoreController', ['BookFactory','$scope',function(BookFactory,$scope) {
var store = this;
$scope.store.products = [];
$scope.queryParam="php";
this.submitQuery = function() {
var param=$scope.queryParam;
BookFactory.setQuery(param);
BookFactory.callBooks()
.then(function(data){
store.products = data;
}, function (data) {
alert(data);
});
}
this.submitQuery();
}]);
and you can set up value of input and thus pass query param to contoller
Thanks for your answer
Not only in ng-repeat is happening. I mean, even if store.submitQuery('php') executes without ng-repeat, the result will be the same (infinity loop).
However for me from semantic point of view to use additional html element for this is not very good.
I changed the view like this:
<div ng-init="store.init('php')" ng-controller="StoreController as store">
{{store}}
</div>
And little bit the controller:
app.controller('StoreController', ['BookFactory',function(BookFactory) {
var store = this;
store.products = [];
this.init = function(param) {
BookFactory.setQuery(param);
this.submitQuery();
}
this.submitQuery = function(param) {
BookFactory.callBooks()
.then(function(data){
store.products = data;
}, function (data) {
alert(data);
});
}
}]);
And now it’s working like I need, but I’m not sure this is the right way.
I am really new to angular and have been reading a number of tutorials etc and have the following problem:
search-module.js
var Search = angular.module('SearchApp',["ngCookies","ngRoute"]);
Search.run(function ($http, $cookies) {
$http.defaults.headers.common['X-CSRFToken'] = $cookies['csrftoken'];
});
Search.config(function($routeProvider){
$routeProvider
.when('/', {
controller:'searchCtrl',
resolve: {
inv_items: function (InventoryService){
return InventoryService.get('red');
}
}
})
.otherwise({
redirectTo: '/'
})
});
data-service.js
Search.factory('InventoryService', function ($http, $q) {
var api_url = "api/inventory/";
return {
get: function (inventory) {
var url = api_url + inventory;
var defer = $q.defer();
$http({method: 'GET', url: url}).
success(function (data, status, headers, config){
defer.resolver(data);
})
.error(function (data,status, headers, config){
defer.reject(status);
});
return defer.promise;
}
}
});
search-controller.js
Search.controller('searchCtrl', function($scope){
$scope.selected = 'have';
$scope.setSection = function(section){
$scope.selected = section;
};
$scope.isSelected = function(section){
return $scope.selected == section;
};
});
Like I mentioned previously I am really new to angular just picked it up yesterday. Basically from what I have written I understand that when the URL is '/' then the service will be initiated and the controller will be called? What I want to know is why cant I use inv_items in my controller? I get the following error.
Do I need to pass some sort of global to the controller which will contain inv_items or am I missing some important piece of knowledge?
Thanks!
The resolve variable 'inv_items' isn't automatically added to your scope of 'searchCtrl'.
Search.controller('searchCtrl', function($scope, inv_items){ //Add this
$scope.inv_items = inv_items; //And this
$scope.selected = 'have';
$scope.setSection = function(section){
$scope.selected = section;
};
$scope.isSelected = function(section){
return $scope.selected == section;
};
});
Granted that the rest of the code works, your 'inv_items' should now be available in that scope.