I have a json file that includes article information where each article has an id. This is how it is formatted:
[{"title":"ISIS No. 2 killed in US special ops raid",
"id":"14589192090024090",
"agency":"foxnews",
"text":"Article text goes here.",
"topic":"Politics",
"imagePath":"resources\/images\/foxnews\/14589192090024090.img.jpg"},
{"title":", etc etc }]
On my main page I have a list view that shows the title and author and when you click on the article I want it to display the text, topic, etc. My angularJS factory for requesting the json looks like this:
var trooNewsServices = angular.module('trooNewsServices', ['ngResource']);
trooNewsServices.factory('Articles', ['$resource',
function($resource){
return $resource('resources/articles.json');
}]);
I access the full list of articles in my home page controller by using:
this.articles = Articles.query();
What I am struggling with is when I click on a specific article I want that next page to display that articles info. I am attempting to do this by getting the specific id using $routeParams.id and then looking for the id in the json. Here is the code in my selected article controller:
TrooNews.controller('ArticleController', ['$routeParams','Articles',
function($routeParams, Articles) {
//look through articles for specific article using routeparams
Articles.query().$promise.then(function(articles) {
for(i = 0; i < articles.length; i++){
if(articles[i].id===$routeParams.id){
this.selectedArticle=articles[i];
}
}
});
console.log(selectedArticle);
}]);
I get an error 'Could not instantiate controller ArticleController'. How can I access my selectedArticle variable outside the promise function?
TrooNews.controller('ArticleController', ['$routeParams','Articles',
function($routeParams, Articles) {
var parent = this;
parent.selectedArticle = null;
parent.setSelectedArticle = function(article){
parent.selectedArticle = article;
}
//look through articles for specific article using routeparams
Articles.query().$promise.then(function(articles) {
for(i = 0; i < articles.length; i++){
if(articles[i].id===$routeParams.id){
parent.setSelectedArticle(articles[i])
break;
}
}
});
}]);