Retrieving posts by id - javascript

I am receiving a JSON object from WordPress which looks like this
{
"ID": 4164,
"title": "24 Horas Non-Stop con Marco Carola",
"status": "publish",
"type": "post",
"author": {
"ID": 11,
"username": "VIlma Quiros",
"registered": "2015-04-16T07:04:04+00:00",
"meta": {
"links": {
"self": "http://urbanetradio.com/wp-json/users/11",
"archives": "http://urbanetradio.com/wp-json/users/11/posts"
}
}
},
"content": "<p class=\"p2\"><a href=
here is my service
.service('FreshlyPressed', function($http, $q) {
return {
getBlogs: function($scope) {
var posts = [];
$http.get('http://urbanetradio.com/wp-json/posts')
.success(function(result) {
$scope.posts = result;
})
},
getPostById: function(postId) {
var url ='http://urbanetradio.com/wp-json/posts/postId';
return $http.get(url);
}
});
and here the controller
.controller('NewsCtrl', function($scope, FreshlyPressed) {
$scope.posts = [];
$scope.doRefresh = function() {
$scope.posts = FreshlyPressed.getBlogs($scope);
$scope.$broadcast('scroll.refreshComplete');
}
$scope.doRefresh();
});
and here is what I want:
in this view I display only the title and the date of the posts, this is the main view
<a ng-href="#/tabs/news/{{post.ID}}">
<h2 ng-bind-html="post.title"></h2>
<p>{{:: post.date | date}}</p>
</a>
when you click in that title you should be redirected to the entired post which is here, in the secondary view
<div class="item item-text-wrap item-image padding">
<div class="special-font" ng-bind-html="post.content"></div>
</div>
the routes
//the route for the main view
.state('tabs.news', {
url: '/news',
views: {
'tab-news': {
templateUrl: 'templates/tab-news.html',
controller: 'NewsCtrl'
}
}
})
//the route for the second view where you will see the entire post
.state('tabs.post-detail', {
url: '/news/:postId',
views: {
'tab-news': {
templateUrl: 'templates/tab-post-detail.html',
controller: 'PostDetailCtrl'
}
}
})
I get this error
GET http://urbanetradio.com/wp-json/posts/postId 404 (Not Found)

I guess you need to change this function like this
getPostById: function(postId) {
var url ='http://urbanetradio.com/wp-json/posts/'+ postId;
return $http.get(url);
as per you code postId is parameter that you want to replace in string than you should append value in string as in code
you need to call method like
FreshlyPressed.getPostById(1);//1 is postid value

Related

Loading data from JSON file in to Javascript object

I am trying to access the data from my JSON file to be used within my controller for further manipulation using Angular. To start, here are the first couple entries of the file 'cards.json'
{ "TheGrandTournament": [
{
"name": "Buccaneer",
"cardSet": "The Grand Tournament",
"type": "Minion",
"rarity": "Common",
"cost": 1,
"attack": 2,
"health": 1,
"text": "Whenever you equip a weapon, give it +1 Attack.",
"collectible": true,
"playerClass": "Rogue",
"img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_029.
},
{
"name": "Competitive Spirit",
"cardSet": "The Grand Tournament",
"type": "Spell",
"rarity": "Rare",
"cost": 1,
"text": "<b>Secret:</b> When your turn starts, give your minions +
"collectible": true,
"playerClass": "Paladin",
"img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_073.
"mechanics": [{"name": "Secret"}]
}, ...
]}
I have had success with accessing the information from my view using this code
<div ng-controller="CardCtrl">
<button id="loadbtn" ng-click="load()">Load</button><br>
<div ng-repeat="cards in data.TheGrandTournament | limitTo:2">
<pre>{{ cards.name }}</pre>
</div>
</div
My controller looks like this:
angular.module('cards', []).controller('CardCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.method = 'GET';
$scope.url = 'cards.json';
$scope.load = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url}).
then(function(response) {
$scope.data = response.data;
console.log("Read file", $scope.url, "successfully.");
}, function(response) {
$scope.data = response.data || "Request failed";
console.log("Error reading", $scope.url, ".");
});
};
$scope.cardData = angular.fromJson($scope.data[0]);
console.log($scope.cardData);
}]);
The error returned when trying to output $scope.cardData to a console log is
"TypeError: Cannot read property '0' of undefined".
I tried then parsing the data from the json object using angular.fromJson() but it is not working as I am intending.
You should move $scope.data into the success callback of the promise:
$http({method: $scope.method, url: $scope.url}).
then(function(response) {
$scope.cardData = response.data.TheGrandTournament;
console.log("Read file", $scope.url, "successfully.");
console.log($scope.cardData);
}, function(response) {
$scope.data = response.data || "Request failed";
console.log("Error reading", $scope.url, ".");
});
// scope parameter data is not accessible here, as it's not yet added
//$scope.cardData = angular.fromJson($scope.data[0]);
//console.log($scope.cardData);
}]);
Replace:
$scope.data = response.data;
with:
$scope.data = response.data.TheGrandTournament;
Try to replace:
$scope.cardData = angular.fromJson($scope.data[0]);
with:
$scope.cardData = angular.fromJson($scope.data["TheGrandTournament"][0]);

Angular UI-Router dynamic routing based on slug from API Ajax Call. Load view based on slug

Examples slugs in server database accessible through API:
{slug: "john-smith",type: "user"}
{slug: "microsoft-technologies",type: "company"}
scenario 1 : user view & controller : http://localhost/john-smith
.state('user', {
url: '/:user',
templateUrl: 'partial-user.html',
controller: 'userCtrl'
})
scenario 2 : company view & controller : http://localhost/microsoft-technologies
.state('company', {
url: '/:company',
templateUrl: 'partial-company.html',
controller: 'companyCtrl'
})
Now I want to make make a dynamic state based the slug getting from API Call to the server.
I written a imaginary code. But I'm not getting way to achieve
// Example URL http://localhost/john-smith
.state('hybrid', {
// /john-smith
url: '/:slug',
templateUrl: function () {
return "partial-"+type+".html"
},
controllerProvider: function (rt) {
return type+'Controller'
},
resolove: {
type: function ($http, $stateParams) {
$http.get({
method: "GET",
url: "http://localhost/api/" + $stateParams.slug
}).success(function(response, status, headers, config){
//response = {slug: "john-smith",type: "user"}
return response.type
})
return
}
}
})
There is a working plunker.
It comes from similar issue: AngularJS ui-router - two identical route groups
In case, I do understand your aim properly, this would be the adjusted state definition (I just skipped the $http and server response part, just working with passed parameter):
.state('hybrid', {
// /john-smith
url: '/{slug:(?:john|user|company)}',
templateProvider: ['type', '$templateRequest',
function(type, templateRequest)
{
var tplName = "tpl.partial-" + type + ".html";
return templateRequest(tplName);
}
],
controllerProvider: ['type',
function(type)
{
return type + 'Controller';
}
],
resolve: {
type: ['$http', '$stateParams',
function($http, $stateParams) {
/*$http.get({
method: "GET",
url: "http://localhost/api/" + $stateParams.slug
}).success(function(response, status, headers, config){
//response = {slug: "john-smith",type: "user"}
return response.type
})*/
return $stateParams.slug
}
]
}
})
One change is the resolove : {} became: resolve : {}. Another is fixture of the controller def (rt vs type). And also, we do profit from built in features templateProvider and $templateRequest (similar here: Angular ui.router reload parent templateProvider)
check that in action here
EXTEND, including the $http part (extended plunker)
Let's adjust (for plunker purposes) the server part to return this info as data.json:
{
"john-smith": {"type": "user"},
"lady-ann": {"type": "user"},
"microsoft-technologies" : {"type": "company" },
"big-company" : {"type": "company" },
"default": {"type" : "other" }
}
And these links:
<a href="#/john-smith">
<a href="#/lady-ann">
<a href="#/microsoft-technologies">
<a href="#/big-company">
<a href="#/other-unknown">
Will be easily managed by this adjusted state def:
.state('hybrid', {
// /john-smith
url: '/:slug',
templateProvider: ['type', '$templateRequest',
function(type, templateRequest)
{
var tplName = "tpl.partial-" + type + ".html";
return templateRequest(tplName);
}
],
controllerProvider: ['type',
function(type)
{
return type + 'Controller';
}
],
resolve: {
type: ['$http', '$stateParams',
function($http, $stateParams) {
return $http.get("data.json")
.then(function(response){
var theType = response.data[$stateParams.slug]
||response.data["default"]
return theType.type
})
}
]
}
})
Check that updated stuff here

Javascript: Show Image from Json with AngularJs

I have a Json that contains this:
[
{
"_id": "00000",
"title": "",
"genre": "fantasy",
"year": "1999",
"image": "photo.jpg"
}
]
I use AngularJs and I want show image in my page html. This is the code:
<div>
<h2>Films</h2>
<div>
<div ng-repeat="book in lista">
<div>
<img ng-src="{{book.cover}}" style="width: 256px; height: 128px;">
</div>
</div>
</div>
</div>
and this is my controller:
var modulo = angular.module('progetto', ['ngRoute']);
modulo.config(function ($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'list.html',
controller: 'listController'
})
});
modulo.controller('listController', function ($scope, $http) {
$http.get('http://.......').success(function (data) {
$scope.lista = data;
}).
error(function (data, status) {
$scope.lista = "Request failed";
});
});
how do I show the photo? Because the photo is a jpg. Thanks!
You might want to call $scope.$apply() after every http request which are modifying the model and the new value needs to be communicated to the view.
lo.controller('listController', function ($scope, $http) {
$http.get('http://.......').success(function (data) {
$scope.lista = data;
$scope.$apply();
}).
error(function (data, status) {
$scope.lista = "Request failed";
$scope.$apply();
});
});

Angular js display name based on selected item and url path

I am starting out on the angular seed. I have a json file that displays items like the below.
{
"id":"1",
"name":"Spain",
"abbrev":"esp"
}
When I click on a country in the list I want to the display the details such as the name for this item.
I have this working as shown below.
/* app.js */
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', ['ngRoute','myApp.controllers','myApp.services'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'templates/view1.html',
controller: 'CountryCtrl'
});
}])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/:name', {
templateUrl: 'templates/view2.html',
controller: 'CountryCtrl'
});
}])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/'});
}]);
/* services.js */
angular.module('myApp.services', [])
.factory('Countries', ['$http', function($http) {
var Countries = {};
Countries.name = '';
Countries.listCountries = function () {
return $http.get('../api/countries');
},
Countries.ChangeName = function (value) {
Countries.name = value;
}
return Countries;
}]);
/* controllers.js */
angular.module('myApp.controllers', [])
.controller('CountryCtrl', ['$scope', 'Countries', '$location', function($scope, Countries,$location) {
listCountries();
function listCountries() {Countries.listCountries()
.success(function (data, status, headers, config) {
$scope.countries = data.countries;
})
.error(function(data, status, headers, config) {
$scope.status = 'Unable to load data: ' + error.message;
});
}
$scope.name = Countries.name;
$scope.changeView = function(countryName,indx){
$location.path(countryName);
$scope.name = Countries.ChangeName(countryName);
}
}]);
/* templates/view1.html */
<ul>
<li ng-repeat="country in countries">
<div ng-click="changeView(country.name,$index)">{{country.name}}</div>
</li>
</ul>
/* templates/view2.html */
{{name}}
What I can't get to work is that if I go to http://www.example.com/app/#/ then navigate to spain in the list then I get taken to http://www.example.com/app/#/esp and {{name}} gets outputted as esp.
However if I navigate straight to http://www.example.com/app/#/esp without first clicking on spain in the list I get no value in my $scope.name
How can I achieve this?
I want the name to also be set based on the location path if it is available.
I know that $location.$$path will get me /esp however I don't really think this is the best idea to use this incase the url builds out to something bigger eg http://www.example.com/app/#/esp/events
can I some how access the index or id of the item so that I can then access the data like
{{countries[0].name}}
where 0 is id of esp - 1.
What is the best approach?
Mate, there are a couple of issues with your app.
Your service retains "state" although is only used to retrieve information
You're using the same controller to 2 different views (bad practice)
$scope.status = 'Unable to load data: ' + error.message; --> Error is not defined
There are a couple of js errors too, like strayed commas and stuff
Anyways, here's a revised version of your code. Fiddle
// Instantiate your main module
var myApp = angular.module('myApp', ['ngRoute']);
// Router config
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'templates/view1.html',
controller: 'CountryListCtrl'
})
.when('/:id', {
templateUrl: 'templates/view2.html',
controller: 'CountryCtrl'
})
}
]);
// Your Factory. Now returns a promise of the data.
myApp.factory('Countries', ['$q',
function($q) {
var countriesList = [];
// perform the ajax call (this is a mock)
var getCountriesList = function() {
// Mock return json
var contriesListMock = [{
"id": "0",
"name": "Portugal",
"abbrev": "pt"
}, {
"id": "1",
"name": "Spain",
"abbrev": "esp"
}, {
"id": "2",
"name": "Andora",
"abbrev": "an"
}];
var deferred = $q.defer();
if (countriesList.length == 0) {
setTimeout(function() {
deferred.resolve(contriesListMock, 200, '');
countriesList = contriesListMock;
}, 1000);
} else {
deferred.resolve(countriesList, 200, '');
}
return deferred.promise;
}
var getCountry = function(id) {
var deferred = $q.defer();
if (countriesList.length == 0) {
getCountriesList().then(
function() {
deferred.resolve(countriesList[id], 200, '');
},
function() {
deferred.reject('failed to load countries', 400, '');
}
);
} else {
deferred.resolve(countriesList[id], 200, '');
}
return deferred.promise;
}
return {
getList: getCountriesList,
getCountry: getCountry
};
}
]);
//Controller of home page (pretty straightforward)
myApp.controller('CountryListCtrl', ['$scope', 'Countries',
function($scope, Countries) {
$scope.title = 'Countries List';
$scope.countries = [];
$scope.status = '';
Countries.getList().then(
function(data, status, headers) { //success
$scope.countries = data;
},
function(data, status, headers) { //error
$scope.status = 'Unable to load data:';
}
);
}
]);
// controller of Country page
// Notice how we use $routeParams to grab the "id" of our country from the URL
// And use our service to look for the actual country by its ID.
myApp.controller('CountryCtrl', ['$scope', '$routeParams', 'Countries',
function($scope, $routeParams, Countries) {
$scope.country = {
id: '',
name: '',
abbrev: ''
};
var id = $routeParams.id;
Countries.getCountry(id).then(
function(data, status, hd) {
console.log(data);
$scope.country = data;
},
function(data, status, hd) {
console.log(data);
}
);
}
]);
In your "CountryCtrl", if you include $routeParams and use $routeParams.tlaname, you will have access to the tlaname. You can then use that to initialize your data.

Angular JS TypeError: Cannot read property 'id' of undefined on Route

I'm in the process of learning a bit of AngularJS and I've hit a stumbling block. I can retrieve my jSON and feed it into the frontend, but my problem is coming when I'm going to a new view. My ID is not coming in correctly. Basically if click on my item that has a id 1 its displaying id 14. Or I get TypeError: Cannot read property '14' of undefined
Any ideas would be really helpful.
jSON
[
{
"id": 14,
"title": "new post",
"excerpt": "EXCERPT",
"content": "ushajsd"
},
{
"id": 10,
"title": "last post",
"excerpt": "test",
"content": "test"
},
{
"id": 4,
"title": "middle post",
"excerpt": "contents to post",
"content": "contents to post"
},
{
"id": 1,
"title": "Hello world!",
"excerpt": "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!",
"content": "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!"
}
]
AngularJS
//Create main module
var module = angular.module('module', [''])
//Services
module.factory('posts', function($http) {
return {
getAsync: function(callback) {
$http.get('/wp-content/themes/ajax/ajax.php').success(callback);
}
};
});
// Set up our mappings between URLs, templates, and controllers
function caseStudyConfig($routeProvider) {
$routeProvider.
when('/casestudy/:id', {
controller: caseCtrl,
templateUrl: '/wp-content/themes/templates/casestudy.php'
}).
otherwise({
redirectTo: '/'
});
}
// Set up our route so the service can find it
module.config(caseStudyConfig);
//Controllers
function homeCtrl (posts, $scope) {
posts.getAsync(function(data) {
$scope.content = data;
});
}
function caseCtrl (posts, $scope, $routeParams) {
posts.getAsync(function(data) {
$scope.content = data[$routeParams.id];
});
}
Assuming the data property in your getAsync callback is a representation of the JSON you've posted, I think it's because you're attempting to access the object by it's position in the array and not by its id property. If you're using underscore / lodash, you could fix this easily like so:
function caseCtrl (posts, $scope, $routeParams) {
posts.getAsync(function(data) {
// Find the object with id which matches id in route params
$scope.content = _.findWhere(data, { id: $routeParams.id });
});
}
Or you could write your own loop to retrieve the correct object from the collection:
function caseCtrl (posts, $scope, $routeParams) {
posts.getAsync(function(data) {
$scope.content = getObjectById(data, $routeParams.id);
});
function getObjectById(collection, id) {
for (var i = 0, obj; i < collection.length; i ++) {
obj = collection[i];
if (obj.id === id) {
return obj;
}
}
return null;
}
}

Categories

Resources