I'm trying to create a simple movie app in Angular. I can do a JSON request to the tmdb (the movie database) api and show the raw result on my homepage. But my problem is that I can't seem to only show the title of the movies from the JSON request.
examplecontroller.js.coffee
angular.module('app.exampleApp').controller('exampleCtrl', [
'$scope', '$http', function($scope, $http) {
var base = 'http://api.themoviedb.org/3';
var service = '/movie/popular';
var apiKey = 'a8f703963***065942cd8a28d7cadad4';
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + service + '?api_key=' + apiKey + '&callback=' + callback;
$scope.movieList = 'requesting...';
$http.jsonp(url).then(function(data, status) {
$scope.movieList = JSON.stringify(data);
console.log($scope.movieList)
},function(data, status) {
$scope.movieList = JSON.stringify(data);
});
}
]);
show.html.haml
#search{"ng-app" => "app.exampleApp"}
%div{"ng-controller" => "exampleCtrl"}
%div{"ng-repeat" => "movie in movieList track by $index"}
{{movie.title}}
When I check the elements in Chrome I see that I have about 25.000 ng-repeat divs. But all without content.
I've been following this tutorial for a bit (and some other sources) and something I don't understand is the movie in Movielist. I know that movielist is the whole json request but what is movie?
Solved
controller
angular.module('app.exampleApp').controller('exampleCtrl', [
'$scope', '$http', function($scope, $http) {
var base = 'http://api.themoviedb.org/3';
var service = '/movie/popular';
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4';
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + service + '?api_key=' + apiKey + '&callback=' + callback;
$scope.movieList = [];
$http.jsonp(url).
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.')
});
}
]);
show
%h1
Logo
%li
= link_to('Logout', destroy_user_session_path, :method => :delete)
#search{"ng-app" => "app.exampleApp"}
%div{"ng-controller" => "exampleCtrl"}
%div{"ng-repeat" => "movie in movieList"}
{{ movie.original_title }}
Your problem is you are taking the javascript array returned to the request callback as data and converting it into a string using JSON.stringify().
Then when you pass this string to ng-repeat it is looping over every character in that string. Thus you have a huge number of repeated <div> but since each is a string containing one character there is no title property of that string to print
Pass the array directly to your scope variable in the request callback.
Change:
$scope.movieList = JSON.stringify(data);
To:
$scope.movieList = data;
JSON is a string data format. When $http receives that string response it will internally parse it to a javascript object/array. You should not need to transform it yourself
Related
Hi I am trying to retrieve some data from webservice using AngularJS $http get.
I have the following code snippet:
In the servicesjs:
.factory('BoothDesignatedCoordsService', ['$http', function ($http) {
var factory = {};
factory.getBoothDesignatedCoords = function (strBoothName, intFloorPlanID) {
var sendToWS;
var boothDesignatedCoords
var JSONObj = {
BoothName: strBoothName,
FloorPlanID: intFloorPlanID
};
sendToWS = JSON.stringify(JSONObj)
var urlBase = 'http://localhost:4951/wsIPS.asmx/fnGetBoothDesignatedCoords?objJSONRequest=' + sendToWS;
return $http.get(urlBase)
}
return factory;
}])
In the controllerjs:
var boothDesignatedCoords = BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3).success(function (response, data, status) {
console.log("successfully send booth name and floor plan id to ws");
console.log("data " + data + " , status : " + status);
console.log("data " + data);
boothDesignatedCoords = data;
for (var c = 0; c < boothDesignatedCoords.length; c += 2) {
}
The $http get is successful as I am able to print "successfully send booth name and floor plan id to ws" in the browser console log.
When I tried to print console.log("data " + data), it gives me some values of an integer array. That is exactly what I want. But in the controller I tried to assign data to the variable boothDesignatedCoords, the program does not run the for loop. Am I missing some code?
EDIT:
I tried to trace the code ( trace the variable called "data" in the controllerjs) and it says "data is not defined"
You appear to be confused about the methods available on the $http promise and their arguments. Try this
BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3)
.then(function(response) {
var data = response.data
var status = response.status
console.log('data', data) // note, no string concatenation
// and so on...
})
FYI, the success and error methods have been deprecated for some time and removed from v1.6.0 onwards. Don't use them.
I also highly recommend passing query parameters via the params config object
var urlBase = 'http://localhost:4951/wsIPS.asmx/fnGetBoothDesignatedCoords'
return $http.get(urlBase, {
params: { objJSONRequest: sendToWS }
})
This will ensure the key and value are correctly encoded.
csMgmtApp.controller('launchedController', ['$scope', '$http', '$document', '$resource', function ($scope, $http, $document, $resource) {
$scope.clientResult = {};
$scope.data = {};
$document.ready(function () {
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0; i < vars.length; i++) {
var pair = vars[i].split("=");
query_string[pair[0]] = pair[1];
}
if (typeof(query_string.access_token) != "undefined") {
var result = {};
result.state = query_string.state;
result.scope = query_string.scope;
result.access_token = query_string.access_token;
result.expires_in = query_string.expires_in;
result.resource_server_base_uri = query_string.resource_server_base_uri;
result.token_type = query_string.token_type;
}
$scope.clientResult = result;
});
console.log($scope.clientResult);
$scope.startSessionPayload = {
'stationPhoneNumber': '5555555555',
'inactivityTimeout': '0',
'inactivityForceLogout': 'false'
};
$http({
'url': $scope.clientResult.resource_server_base_uri + 'services/v6.0/agent-sessions',
'method': 'POST',
'headers':{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
'data': JSON.stringify($scope.startSessionPayload)
}).success(function(data, status, headers, config) {
$scope.data = data;
console.log('data', $scope.data)
}).error(function(data, status, headers, config) {
$scope.status = status;
});
}]);
The code above gives me a 404 when I try te $http "POST".
When I console.log($scope.clientResult.resource_server_base_uri), I get: "https%3a%2f%2fapi-c7.incontact.com%2finContactAPI%2f".
But, I get a 404, and when I look in developer tools, I see it's trying to post to : "http://localhost:63342/Call_cntr/client/https%3a%2f%2fapi-c7.incontact.com%2finContactAPI%2fservices/v6.0/agent-sessions"
I'm starting to think it's failing because the "://localhost..." is being "prepended" to the base_uri... Not sure why this is happening. I feel I'm providing everything mentioned in the inContact API docs. Maybe it's with my angular conversion from AJAX to $http ??
Any help, much appreciated, I'm stuck..
Once you have an API Authentication Token, you use this token to create an agent session for the agent whose credentials you used to get the token. This is done by requesting the https://api-{cluster}.incontact.com/inContactAPI/services/v6.0/agent-sessions method, and supplying either a "station ID" or a phone number which will be delivered to the agent.
per the docs : https://developer.incontact.com/API/AgentAPI#!/Sessions/startSession
Try
result.resource_server_base_uri = unescape(query_string.resource_server_base_uri);
I believe that / is actually a seperator, but %2f becomes an ordinary character that simply represents / character in your url.
unescape() is deprecated; try decodeURIComponent()
I am trying to set the controllers scope variable to the data, however no luck. The console.log in the controller shows undefined. Appreciate the help!
My angular service has the following code --
service('VyrtEventService', ['$http', function($http) {
var events = [];
this.getArtistEvents = function(artistId) {
var url = '/api/users/' + artistId + '/';
var promise = $http.get(url).success(function(data, status, headers, config) {
events = data.artist.events;
console.log(events);
return events;
}).catch(function(error) {
status = 'Unable to load artist data: ' + error.message;
console.log(status);
});
return promise;
};
}]);
And I am referencing it in the controller as follows --
VyrtEventService.getArtistEvents($scope.artistId).then(function(data){
$scope.events = data.data.artist.events;
});
console.log($scope.events);
You should just set $scope.events = data in your controller cause your promise already returns data.artist.events when it resolves
To pass scope to service from anywhere in controller. Make sure you inject service .
controllersModule.controller('MyCtrl', function($scope, $filter, $http, $compile, ngTableParams, **FactoryYouwant**)
{
**FactoryYouwant**.getdata($scope.**scopeYoutwantTopass**).then (function(responseData){
var ResponseFromServer =responseData.data;
}
in service
controllersModule.factory('**FactoryYouwant**, function($http) {
var responseData = null;
return {
getdata : function(**data**){ (you dont have to use $)
responseData = $http.post or whatever actually gets you data;
return responseData;
}
};
});
I hope this helps you to call get data from service anywhere in controller.
I'm writing a search script to return a bunch of HTML, but it doesn't seem to be working, I'm trying to use $sce.
function SearchCtrl($scope, $http, $sce) {
$scope.url = 'search.php'; // The url of our search
// The function that will be executed on button click (ng-click="search()")
$scope.search = function() {
// Create the http post request
// the data holds the keywords
// The request is a JSON request.
$http.post($scope.url, { "data" : $scope.keywords}).success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.result = data;
$scope.trustedExample = $sce.trustAsHtml(data);
// Show result from server in our <pre></pre> element
})
};
}
Have I done it incorrectly?
Link to the test site is here: http://elliottcoe.com/search/
I was trying to get stock quotes from yahoo api.
My input to the query is only a stock ticker ( from a text field). On button click the background JavaScript method "getprice()" is called.
I have a java script code that looks like this
function getprice()
{
var symbol = $('#stockquote').val();
var url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22"+symbol+"%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json";
$.getJSON(url, function (json)
{
var lastquote = json.query.results.quote.LastTradePriceOnly;
$('#stock').text(lastquote);
});
}
$('#stock').text(lastquote);
Here "stock" is the text field where I want to display the LastTradePriceOnly for the given ticker.
I do not see any output turning up.
Debugging also does not show up any errors.
Can I get any suggestions with this issue?
Try this.
function getData() {
var url = 'http://query.yahooapis.com/v1/public/yql';
var symbol = $("#symbol").val();
var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");
$.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
.done(function (data) {
$('#result').text("Price: " + data.query.results.quote.LastTradePriceOnly);
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log('Request failed: ' + err);
});
}
Here I also added working example for you.
This is how it's done in AngularJS in case you need it:
In your view:
<section ng-controller='StockQuote'>
<span>Last Quote: {{lang}}, {{lastTradeDate}}, {{lastTradeTime}}, {{lastTradePriceOnly}}</span>
</section><br>
In your controller: The stock symbol name is passed via $scope.ticker_name to service method 'getData.getStockQuote'.
appModule.controller('StockQuote', ['$scope', 'getData',
function($scope, getData) {
var api = getData.getStockQuote($scope.ticker_name);
var data = api.get({symbol:$scope.ticker_name}, function() {
var quote = data.query.results.quote;
$scope.lang = data.query.lang;
$scope.lastTradeDate = quote.LastTradeDate;
$scope.lastTradeTime = quote.LastTradeTime;
$scope.lastTradePriceOnly = quote.LastTradePriceOnly;
});
}]);
In your service:
appModule.service('getData', ['$http', '$resource', function($http, $resource) {
// This service method is not used in this example.
this.getJSON = function(filename) {
return $http.get(filename);
};
// The complete url is from https://developer.yahoo.com/yql/.
this.getStockQuote = function(ticker) {
var url = 'http://query.yahooapis.com/v1/public/yql';
var data = encodeURIComponent(
"select * from yahoo.finance.quotes where symbol in ('" + ticker + "')");
url += '?q=' + data + '&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
return $resource(url);
}
}]);