Unable to retrieve JSON data using Ionic AngularJS framework - javascript

I'm doing Lynda's tutorial on Ionic framework and once I finally got onto some backend coding, I've run into this issue. Basically just generated the app and opened up the www/js/app.js file to add a controller to it with this code:
.controller('ListController', ['$scope', '$http', function($scope, $http){
$http.get('js/data.json').success(function(data){
$scope.artists = data;
});
}]);
www/js/data.json is the .json file with the data that I'm supposed to refer to in the index.html file using this code:
<ion-item ng-repeat='item in artists' class="item-thumbnail-left item-text-wrap">
<img src="img/{{item.shortname}}_tn.jpg" alt="{{item.name}} Photo">
<h2>{{item.name}}</h2>
<h3>{{item.reknown}}</h3>
<p>{{item.bio}}</p>
</ion-item>
But the retrieved data is null, as the img tag shows no value upon inspection, same as any other tag containing the 'item' data reference. What can I try?

you can try replacing data with below code:
$scope.artists = data.artists;
OR
$scope.artists = data.speakers;

Related

How correctly hide/show html by ng-if/ng-show/ng-hide from app.run function?

I try to make correct view loading app.
HTML:
<body>
<loading outerWidth='1000' outerHeight='1000' display='isReady'></loading>
<div class='wrapper' ng-show='isReady'>
</div>
</dody>
JS:
app.run(['$rootScope', '$state', '$stateParams', '$location', '$http', 'userData', function($rootScope, $state, $stateParams, $location, $http, userData) {
$rootScope.isReady = false;
$http.post('services/enter.php', {
}).then(function(response) {
$rootScope.isReady = true;
});
}]);
Basic idea: when app loading show some image/loading gif 'please wait'. Next post request to get data and after request show html. But I have problem to manipulate html from app.rum functiuon - I try use $rootScope. Need suggestions how I can do it better.
Let this answer your question , $httpProvider.interceptors, to handle before and after send ajax request $http and broadcast it.
app.run()
is normally used to initialize your app.
I would suggest you create a controller if you're going to keep manipulating your data inside html. In case the data is shared, avoid rootScope and instead use a service to share data across your app

Having trouble on rendering data to angular

Currently I'm trying to render a specific data on angular with node/express as the backend.
What I'm trying to achieve is whenever a user clicks a specific story, it will link to that specific story page that belongs to a user who created the story.
api.js
apiRouter.get('/:user_name/:story_id', function(req, res) {
User.findOne({ name: req.params.user_name }, function(err, user, next) {
if(err) return next(err);
Story.findById(req.params.story_id, function(err, story) {
if(err) {
res.send(err);
return;
}
res.json({
name: user.name,
story_id: story._id,
content: story.content
});
});
});
});
As for the backend(api) It does show the specific data that I wanted with POSTMAN chrome tool but when it comes to angular I'm really confuse of how to render the data to the html.
service.js
storyFactory.getSingleStory = function(user_name, story_id) {
return $http.get('/api/' + user_name + story_id);
}
controller.js
angular.module('storyCtrl', ['storyService'])
.controller('StoryController', function(Story, $routeParams) {
var vm = this;
Story.getSingleStory($routeParams.user_name, $routeParams.story_id)
.success(function(data) {
vm.storyData = data;
});
});
app.routes.js
.when('/:user_name/:story_id', {
templateUrl: 'app/views/pages/users/single.html',
controller: 'StoryController',
controllerAs: 'story'
})
index.html ( Just going to show the line where it goes to the single.html )
<a href="/{{ main.user.name }}/{{ each._id }}"><h4>{{ each.content }}</h4>
single.html
Hello {{ main.user.name }}
<p>{{ story.content }}</p>
So far I couldn't manage to render the data properly with angular while with node/express I could query the data that I wanted with POSTMAN. I'm clueless and please save me from this confusion that angular giving me :)
I have went through your code, and you can improve in following parts:
Instead of using var vm = this in your controller, you should bind all objects to $scope, which is the key to two-way data binding. For instance
angular.module('storyCtrl', ['storyService'])
.controller('StoryController', function($scope, Story, $routeParams) {
var vm = this;
Story.all().success(function(data) {
$scope.stories = data;
});
Then stories can be accessed in View directly. It would be more readable than controllerName.stories in HTML.
<div class="col-md-6" ng-controller="StoryController as story">
<div class="panel-body" ng-repeat="story in stories">
<div class="comment-text">
<h4>{{ story.content }}</h4>
</div>
</div>
</div>
Keep in mind, then(function(response)) will only pass one parameter to the chained function while .success(function(data, status, headers, config)) will retrieve data from HTTP response. Then your code to load single story can be converted to
Story.getSingleStory($routeParams.user_name, $routeParams.story_id)
.then(function(data, status, headers, config) {
$scope.storyData = data;
});
Now we can access storyData in View.
There is a tiny bug in your Story Service. Change generateReq('GET', '/api/' + user_name + story_id) to generateReq('GET', '/api/' + user_name + '/' + story_id)
If you want to set values on the controller and see them in the html view. Set the view model on the controller's scope rather than using this. This and scope are not always the same thing and for binding I believe you need scope.
these expressions
// file: single.html
{{ main.user.name }}
<p>{{ story.content }}</p>
don't seem to be bound to any variable in 'StoryController'
Try using
// file: single.html
{{ story.storyData.user.name }}
<p>{{ story.storyData.content }}</p>
Your problem may be due to the fact that you story data is html and is therefore untrusted by default. For security reasons Angular will not allow you to render html directly into the page, instead you must explicitly tell Angular to trust the html content
To do this you must first include the ngSanitize module in your app.
angular.module('app', ['ngSanitize']);
You can then inject the $sce service which allows you to trust the html content. The code below has a data item with a property called Html that contains raw html text returned from an api. I just overwrite this raw html text with the $sce trust object returned from the $sce.trustAsHtml() method.
item.Html = $sce.trustAsHtml(item.Html);
Once you have trusted your html, you are now free to render it using the ng-bind-html attribute.
<div ng-bind-html="item.Html"></div>
For more information and further examples see:
Insert HTML into view using AngularJS
ngBindHtml

loading data from json files

Im trying to figure something out. If I want to load JSON data from a local file in my angular app, is there a way for me to include or to read the file in angular, or do I need to use some file API to read from the file and store the objects in a array. ty
you can use $http for loading json data from json file
var name = angular.module("app", []);
name.controller("ctrlu", ['$scope','$http', function($scope, $http)
{
$http.get('js/data.json').success (function(data){
$scope.guitarVariable = data;
});
}]
);
Note:you don't need to include(reference) json file in index.html page

Angular JS/ Html queries on Ionic

Im working on a simple todo app tutorial online based on:
http://ionicframework.com/docs/guide/building.html
What if I wanted a database where instead of a fixed list like in the example, there would be a store where users can input their list dynamically, with room for edit and comments on their tasks outstanding?
a paragraph of text
user name noted
timestamp
It would then appear as a todo list that upon clicking, would open up to be editable and able to add more comments to it?
I have followed a couple of tutorials but all of them use fixed data sets.
I did some research and got the below snippets, my understanding of Angular is still weak so am not exactly clear how the codes work.
Something isnt working and Im not sure why. Can anyone explain and help?
Specifically on params and how id comes into play, as well as the convention of url routing, like #/something.html etc.
The tutorial has firebase back end but if you have any better suggestions (like server and back end language), please let me know. Ive seen tutorials using JSON but again, not sure how that works.
For app.js
.state('bucket.list.detail',{
url: '/list/:itemId',
views: {
'bucket-list-detail':{
templateUrl: 'templates/bucket-list-detail.html',
controller: 'DetailController'
}
}
})
For controller.js
.controller('DetailController', function($rootScope, $scope, $stateParams, $window, $firebase){
$scope.item = items.get($stateParams.itemId);
})
For the view file, bucket-list-detail.html
(I just typed in some trash lines to test the code)
<p>{{ item.item }}</p>
<p>
<a class="button button-small icon ion-arrow-left-b"
href="#/bucket/list"> Main List </a>
</p>
First in your question you have items.get in your controller but nowhere did you define items. Since $firebase is probably a factory of some kind you will probably need to either use that or build some service that is getting your data (via firebase or however).
As an example, I've built a sample todo app using .NET (web api) and Ionic that you can see the source code on github. The overall strategy for firebase should be similar.
I have a route like this, very similar to yours. This is for the details view:
.state('tab.tarea-detail', {
url: '/tarea/:tareaId',
views: {
'tab-friends': {
templateUrl: 'templates/_detalle.html',
controller: 'TareaDetailCtrl'
}
}
})
The state param will contain tareaId.
The list view has an ngRepeat with a link containing the id of a todo (tarea in spanish).
<ion-item ng-repeat="tarea in tareas track by $index" type="item-text-wrap" href="#/tab/tarea/{{tarea.Id}}">{{tarea.Nombre}} {{tarea.Desc}}
<ion-delete-button class="ion-minus-circled" ng-click="tareaEliminar(tarea)">
</ion-item>
And my controller which will receive the id and call a service:
.controller('TareaDetailCtrl', function($scope, $stateParams, tareaService) {
//tareaService is just a wrapper for my ajax stuff, you could call firebase here or you could just use firebase
tareaService.obtener($stateParams.tareaId).then(function (data)
{
$scope.tarea = data;
});
})
The service piece is just calling $http. This is a part of the service:
obtener: function (id)
{
var d = $q.defer();
$http.get(url + '/api/tareadata/obtener/' + id).success(function (data)
{
d.resolve(data);
}).error(function (data, error)
{
d.reject();
});
return d.promise;
}

Read a file from JQuery inside AngularJS

Hi I'm a beginner at programming. I'm trying to put data from a json file into a variable
I want to have AngularJS put text into a html document like this
{{ data.text }}
And the text is based off of a json file I have in the app.js, so I set data using JQuery:
myApp.controller('Ctrl', function ($scope, $http) {
$.getJSON("../static/file.json", function(data) {
$scope.data = data;
});
But nothing shows up initially. When I log $scope.data, it turns out to be undefined. But I know that my json file is correct because if I put all this code in some method that is called like
$scope.foo = function(){$.getJSON("../static/file.json", function(data) {
$scope.data = data;
});}
and have some button activate this, it'll work fine. But I want this to be there initially.
try
$.getJSON("/static/file.json", function(data) {
$scope.data = data;
});
then it load file from web http://xxx/static/file.json, not file system.

Categories