JSON file not importing? - angularjs

I'm still pretty new to AngularJS, but this concerns importing from a JSON document.
I have a list of guitars which I've made all as objects in my JS file (And had it all working correctly), and I use ng-repeat to have all of them display. Now, I want to place those objects in a separate JSON file.
HTML template:
<section id="guitarSections" ng-controller="GuitarCtrl">
<div id="guitarDivs" data-ng-repeat="guitar in guitars">
<img id="guitarImages" src="{{guitar.imageURL}}">
<div id="text">
<h2 class="information">{{guitar.title}}</h2>
<p class="information">Instrument: {{guitar.instrument}}<p>
<p class="information">Color: {{guitar.color}}</p>
<p class="information">Price: {{guitar.price}}</p>
</div>
</div>
<br>
</section>
JS
var app = angular.module("myApp", []);
app.controller("GuitarCtrl", function($scope, $http) {
var url = "data.json";
$http.get(url).then(function(response) {
$scope.guitars = response.data;
});
});
And a small sample of my JSON:
{
"guitars":[
{
"title": "Yamaha Revstar 420",
"brand": "Yamaha",
"instrument": "Electric Guitar",
"color": "Red",
"price": "$499.99",
"details": "Yes",
"imageURL": "YamahaRS420.jpg"
},
{
"title": "Yamaha Pacifica Series PAC012",
"brand": "Yamaha",
"instrument": "Electric Guitar",
"color": "Blue",
"price": "$",
"details": "Yes",
"imageURL": "YamahaPacificaSeriesPAC012.jpg"
}
]}
When I run it on a Python Server (python -m SimpleHTTPServer), the page loads, but none of the content will get imported over and it only shows one guitar section.
ADDITIONAL NOTE: I also inspected the Network, and in the columns with the names of the documents, I happened to notice, in red, '%7B%7Bguitar.imageURL%7D%7D'. Upon examining this, a page pops up and gives me a 404, which says:
Error code 404.
Message: File not found.
Error code explanation: 404 = Nothing matches the given URI.
Though I have checked and ensured that all of my documents' names are not misspelled and that each image can be imported.

First, you expect your JSON to contain an array of guitars, but it actually contains an object with a single attribute named guitars.
Second, you should use ng-src rather than src for your IMG element, to avoid this request to a non-interpolated URL.

Related

Access images from local JSON file on the web page in angularjs

Where am i going wrong?
I want to access images from datahl.json file on the web page but unable to access them.Please check the codes and help me.
If possible please refer the solution to plunker editor.
index.html
<div class="col-sm-4" ng-repeat = "hbl in hbls">
<div class="thumbnail" ng-repeat = "h in hbl.data_list"
style="width:100%;">
<img ng-src="{{h.img}}" alt="" style="height:50vh;">
<div class="caption">
<p><strong>{{h.name}}</strong></p>
</div>
</div>
</div>
app.js This is my js codes
var app = angular.module('hostellApp', []);
app.controller('hostellController', function($scope, hblsFactory){
$scope.hbls;
hblsFactory.getHbls().then(function(response){
$scope.hbls = response.data;
});
$scope.sayHello = function(){
console.log("Hello");
}
});
app.factory('hblsFactory', function($http){
function getHbls(){
return $http.get('datahl.json');
}
return {
getHbls: getHbls
}
});
datahl.json This is my local JSON file
`
{
"view_type": 5,
"title": "Hostels By Locality",
"position": 5,
"data_list":
[
{
"img": "https://s3.us-east-2.amazonaws.com/images-city-
teens/IMG_20180526_1139570.8091572935412125.jpg",
"name": "Mahavir Nagar"
},
{
"img": "https://graph.facebook.com/1666751513414902/picture?
type=large",
"name": null
},
{
"img": "https://s3.us-east-2.amazonaws.com/images-city-
teens/cropped1148015742983667713.jpg",
"name": "New Rajiv Gandhi"
},
{
"img": "https://s3.us-east-2.amazonaws.com/images-city-
teens/cropped998427941.jpg",
"name": "Jawahar Nagar"
}
]
}`
The data you get from your JSON file is not an array but an object. This means that you only need one ng-repeat.
Change your first ng-repeat to ng-repeat="h in hbls.data_list"(added an 's' to hbl) and delete your second ng-repeat.
Working plunker: https://plnkr.co/edit/OOd1M1dNFjSB7uaqZZB6?p=preview

Is there a way to escape dot notation in AngularJS groupBy expression?

I am using this AngularJS filter: https://github.com/a8m/angular-filter#groupby
I have a piece of data (JSON) involving key names containing dots, which seems to be mistaken with nested properties.
Is there a way to prevent the filter from parsing the dot notation or an alternate way to specify the name of the field used for grouping ?
Note: I can't change the way data are build from the server.
My code looks like this :
<div ng-repeat="(key, values) in items | groupBy: 'category_id.name'" >
<div class="item-row">
{{key}}
</div>
<div class="badge-row" ng-repeat="item in values">
{{item.name}}
</div>
</div>
And here is the JSON data I get from the server :
[
{
"id": "1",
"name": "test",
"category_id.name": "Main"
},
{
"id": "2",
"name": "foo",
"category_id.name": "Other category"
},
{
"id": "3",
"name": "bar",
"category_id.name": "Test"
}
]
When running this code, at the moment, I am getting 'undefined' as key value.
Angular Filter uses $parse, so that you can order by fields in nested objects
I have a workaround for this problem. If it helps.
Template:
(key, values) in items | groupBy: rawProperty('category_id.name')
Controller:
$scope.rawProperty = function(key) {
return function(item) {
return item[key];
};
};
JS Bin Demo
Hope it helps.

JSON Data not displaying on Ionic HTML Template

I have been trying to find the reason why my Ionic template is not displaying JSON data. I just started working and reading on ionic framework and angularjs.
please bear with my newbie questions;
1.) what is the error or cause why the json record is not displaying on the HTML?
2.) I have seen plenty of code samples where the Json codes is written on the controller.js instead on the services.js. Which one is standard and safe?
3.) I am having doubts regarding my json output, Can someone please confirm if the format is correct.
You help on this is really appreciated,. thanks in advance
here is my Console status:
Objectconfig: Objectdata: Array[1]0: Array[1]0: Array[1]0:
Objectcapacity: "7"fuelcap: "120"
make: "Nissan"model: "LoadMaster II"platenumber: "TRG0122"
vehiclecode: "TRK0004"vehicleid: "8"wheelnumber: "10"
__proto__: Objectlength: 1__proto__: Array[0]
length: 1__proto__: Array[0]length: 1__proto__: Array[0]headers: (name)status: 200statusText: "OK"__proto__: Object
On my template/HTML file:
<ion-list id="vehicleInformation-list1" class=" " ng-repeat="recs in vehiclerecord">
<ion-item id="vehicleInformation-list-item1" class=" ">Vehicle Model
<span class="item-note">{{ recs.model }}</span>
</ion-item>
</ion-list>
My Controller file:
.controller('vehicleInformationCtrl', function($scope, $http) { // TIP: Access Route Parameters for your page via $stateParams.parameterName
// var _this = this;
$http.get('http://myurlsample.com/webserve/').then(function(vehicleinfo ) {
$scope.vehiclerecord = vehicleinfo.data;
console.log(vehicleinfo);
alert(JSON.stringify(vehicleinfo));
}).catch(function(vehicleinfo)
{
console.log(vehicleinfo);
});
})
my Route.js file contains:
.state('tabsController.vehicleInformation', {
url: '/vehicleinfo',
views: {
'tab4': {
templateUrl: 'templates/vehicleInformation.html',
controller: 'vehicleInformationCtrl'
}
}
})
Via Jsonview a record look like this;
[
[
[
{
vehicleid: "8",
platenumber: "TRG0122",
make: "Nissan",
model: "LoadMaster II",
capacity: "7",
fuelcap: "120",
wheelnumber: "10",
vehiclecode: "TRK0004"
}
]
]
]
If I'm reading your jsonview output correctly, it looks like there's a lot of nesting going on:
[[[{model: "LoadMaster II", ...}]]]
The ng-repeat you have there will only work if the $scope.vehiclerecord looks like this:
[{model: "LoadMaster II", ...}, ... ]
Note that this is simply an array of objects with no nested arrays like your jsonview output.
So the solution is to play with vehicleinfo.data from the http response until you have only an array of objects. Based on the jsonview you have there, this would work:
$scope.vehiclerecord = vehicleinfo.data[0][0];

HTML5 Import and Angular controller binding

Given
I'm using HTML5 web components via the <link rel="import..." construct. Am
able to breakup large HTML markup into smaller portions and import them at will into a container (web page) that puts all the smaller parts together. Cool so far.
Now I want to use Angular data binding to be able to show dynamic content in those smaller pages. In my main Index.html page I am able to declare the ng-app in the first Div tag no problem. The angular.module is declared in that page as well. I can get the binding to work if I put all controller logic into main page.
Problem
I'd like to do is split each controller script shown below to be contained in the imported page and not just in the main index.html where it's working now.
<script>
angular.module('ResultsApp', [])
.controller('CardsController', ['$scope',
function ($scope) {
$scope.results = {
'Passed': '12',
'Failed': '3',
'Warnings': '5',
'Summary': '20'
}
}
])
.controller('ResultsController', ['$scope',
function ($scope) {
$scope.results = [
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" },
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" },
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" },
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" },
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" },
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" },
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" },
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" }
];
}]);
</script>
I've tried putting the controller logic into each imported page but it doesn't seem to work. I am only attempting to use one ng-app defined in main page... Please advise.
Ok if I move the code to a partial page like this, where TestResultsApp is on the main page (Index) call this page "pageheading.html" :
<div class="row" ng-controller="HeaderController">
<div class="col-lg-12">
<h1 class="page-header">
{{header.Title}}
</h1>
<ol class="breadcrumb">
<li class="active">
<i class="fa fa-dashboard">Some Data Here</i>
</li>
</ol>
</div>
</div>
<script>
angular.module('HeaderModule', ['TestResultsApp'])
.controller('HeaderController', ['$scope',
function ($scope) {
$scope.header = { "Title": "Pretty Good, Test Case Results Right here!" }
}])
</script>
The New Error
The partial page, can't find angular... More on this tomorrow...
If I am reading this right, you'll need to use ng-controller on each page that utilizes the controller, and it should work.

$sce:itype Attempted to trust a non-string value in a content requiring a string: Context: resourceUrl

I want to play songs stored in my sails server. Path is http://localhost:4000/images/123.mp3.
In front end, i'm using ng-repeat to list that songs from server.
<div ng-repeat="tones in ringTones track by $index">
<div>
<i ng-show="playpause" class="fa fa-play-circle" ng-click="playpause=!playpause" onclick="plays(event);"><audio id="audio_{{$index}}" ng-src="tones.tonePath"></audio></i>
<i ng-show="!playpause" class="fa fa-pause" ng-click="playpause=!playpause" onclick="stop(event);"></i></div>
</div>
This audio source cause external resource problem
<audio ng-src="tones.tonePath"></audio>
in angular controller, i'm using $sce
$http.get("http://localhost:4000/songs/find").success(function(data){
$rootScope.ringTones=data;
$rootScope.ringTones.push($sce.trustAsResourceUrl(data[0]));
}).error(function(data){
console.log('ERROR');
});
Error is :
Error: [$sce:itype] Attempted to trust a non-string value in a
content requiring a string: Context: resourceUrl
Without using $sce that cause
Error: [$interpolate:interr] Can't interpolate: tones.tonePath
Error: [$sce:insecurl] Blocked loading resource from url not allowed by $sceDelegate policy. URL
This is my JSON from server
[{
"toneName": "2",
"aboutTone": "2",
"duration": 2,
"tonePath": "http://localhost:4000/images/234.mp3",
"createdAt": "2015-08-03T15:40:58.227Z",
"updatedAt": "2015-08-03T15:40:58.227Z",
"id": "55bf8b8a77efb94b32b158c0"
},
{
"toneName": "3",
"aboutTone": "3",
"duration": 3,
"tonePath": "http://localhost:4000/images/123.mp3",
"createdAt": "2015-08-03T15:45:16.120Z",
"updatedAt": "2015-08-03T15:45:16.120Z",
"id": "55bf8c8c77efb94b32b158c1"
}
]
Then how to play external mp3 in my ng-repeat. Help me.
I found solution :
External resource not being loaded by AngularJs
app.filter('trusted', ['$sce', function ($sce) {
return function(url) {
return $sce.trustAsResourceUrl(url);
};
}]);
Then specify the filter in ng-src:
<audio
ng-src="{{tones.tonePath | trusted}}" />
</audio>
Thanks for response.
//first Take data from api
$scope.Data= JSLINQ(data.Data).Select(function (Item) { return Item; })
//Map data as trustable to scope
$scope.Data.items.map(function (i) {
i.Header1 = $sce.trustAsHtml(i.Header1);
});
//UI bind modal data
<p ng-bind-html="x1.Header1 " ng-show="x1.Header1 != null"></p>

Resources