AngularJs search still reads non existent data - javascript

I've come across something so bizarre. I had this below set up to read from a data.json file. It should show up a list of people. Instead it's ignoring the json file and is reading out non existing words! I just want it to read from data.json. Even if I delete "data.json" , the search function still prints out these words which don't exist.
As you can see from the photo, it's showing up a list of words that I DO NOT have stored anywhere in my code or on my server. It's puzzling me.
<body ng-app="personApp">
<div class="container">
<header></header>
<div ng-controller="PersonListCtrl">
<div class="bar">Search:
<input ng-model="query">
</div>
<ul class="">
<li ng-repeat="person in persons | filter:query">{{person.name}}</li>
and
var personApp = angular.module('personApp', []);
personApp.controller('PersonListCtrl', function ($scope, $http) {
$http.get('js/data.json').success(function (data) {
$scope.persons = data;
})
});
data.json
[{
"name": "Mike Doe"
}, {
"name": "Jhon Doe"
}, {
"name": "Sam Doe"
}, {
"name": "Sam Doe"
}, ];

Go to browser console -> Network.
Most probably you will see 304 status of your request, that means ajax request was cached by browser. Either clean cache, add query string to request etc.

Related

Accessing array of objects in an object using Angular

I am trying to have an array of 30 recipes shown on my view with data from an API call.
// app.js
angular.module('recipeApp', [])
.controller('RecipesCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.mainview = [];
$http.get('/API')
.then(function(response) {
$scope.mainview = response.data;
});
// index.html
<html lang="en" ng-app="recipeApp">
<body ng-controller="RecipesCtrl">
{{mainview}} //this outputs the same data shown on the API call.
// when I try 'ng-repeat' nothing shows up at all
// data from API call (this is just a sample of the data. there is really an array of 30 objects in "recipes")
{
"count": 30,
"recipes": [
{
"publisher": "Closet Cooking",
"f2f_url": "http://food2fork.com/view/35382",
"title": "Jalapeno Popper Grilled Cheese Sandwich",
"source_url": "http://www.closetcooking.com/2011/04/jalapeno-popper-grilled-cheese-sandwich.html",
"recipe_id": "35382",
"image_url": "http://static.food2fork.com/Jalapeno2BPopper2BGrilled2BCheese2BSandwich2B12B500fd186186.jpg",
"social_rank": 100,
"publisher_url": "http://closetcooking.com"
},
{
"publisher": "The Pioneer Woman",
"f2f_url": "http://food2fork.com/view/47024",
"title": "Perfect Iced Coffee",
"source_url": "http://thepioneerwoman.com/cooking/2011/06/perfect-iced-coffee/",
"recipe_id": "47024",
"image_url": "http://static.food2fork.com/icedcoffee5766.jpg",
"social_rank": 100,
"publisher_url": "http://thepioneerwoman.com"
},
When I have {{mainview}} in the html, it shows the same as above, but how can I have it so all 30 recipes are looped in the view? I looked into ng-repeat, but I am very new to Angular and couldn't figure it out. Any information on this would be appreciated.
you can use ng-repeat like this:
<body ng-controller="RecipesCtrl">
<ul>
<li ng-repeat="recipe in mainview.recipes">{{recipe}}</li>
</ul>
</body>
It will generate a li element for every recipe in your array. You can access the properties of a recipe using . as you would in javascript.
{{recipe.publisher}}
Note: ng-repeat works with any elements, I used ul and li for show purposes only.
Something like this may help you:
<ul>
<li ng-repeat="recipe in mainview.recipes">
{{recipe.title}}
<br />
- {{recipe.publisher}}
</li>
</ul>
I think you're looking for a view fragment like:
<div data-ng-repeat="item in mainview.recipes">
<div>
<label>Publisher</label><span>{{item.publisher}}</span>
<div>
<div>
<label>Title</label><span>{{item.title}}</span>
<div>
...
</div>
where ... is whatever else you want to display in the view. Documentation at: https://docs.angularjs.org/api/ng/directive/ngRepeat (though I know you've read it (: )

angularjs routeprovider variation

I am quite new with angular, so I am not sure if what I want to do is actually achievable with angular or if it is better to use some other framework.
This is my situation, we have a website made in wordpress, that contains a bit more than 500 pages, all of the pages are the same (exact same content). The main reason they builded this way is:
availability to have custom "domain names", IE:
www.page.com/mypage1
www.page.com/mypage2
www.page.com/mypage...
there is one section on the page that contains an iframe, the iframe is the same on all pages except for a parameter so for instance the iframe of mypage1 has as an url: www.otherpage.com?client=client1Id
So I have use angular before to do a very simple $routeProvider, so I am wondering if I can use the same concept but with some changes
var sampleLandingPage = angular.module('sampleLandingPage', []);
sampleLandingPage.controller('landingPage',['$scope', function ($scope){
$scope.pages = [
{
"FullName": "Client No 1",
"Name": "mypage1",
"CM": null,
"AF": "CLID001",
"OtherURL": null
},
{
"FullName": "Client No 2",
"Name": "mypage2",
"CM": "CLID002",
"AF": "CLID002",
"OtherURL": null
},
{
"FullName": "Client Special",
"Name": "mypage3",
"CM": "CLID002",
"AF": "CLID003",
"OtherURL": "/somethingelse"
}
];
}]);
sampleLandingPage.config(['$routeProvider',
function($routeProvider) {
//$routeProvider.
}]);
so what I want to achieve is if the URL is requesting mypage2; to be able to display CM and AF in my page like {{ CM }} this way I can have only one page but on my iframe have the url like
www.otherpage.com?client={{ CM }}&otherparam={{ AF }}
and have a unique page that looks like
<body ng-app="sampleLandingPage">
<div class="container">
<div ng-controller="landingPage">
page text...
.........
iframe ... url=www.otherpage.com?client={{ CM }}&otherparam={{ AF }}
</div>
</div>
</body>
and finally if the OtherURL param is different to null, then display the actual URL define in this param

AngularJS: How to create a model which holds an array for a dynamic list of input fields?

I have quite an interesting question (I hope) for all you AngularJS gurus out there. I am looking to create a dynamic list of form input fields based on a SELECT dropdown. As an example, we have a number of categories with each category having a set of specifications which are unique to that category. To help with the explanation we have the following:
Firstly, in the controller we start by initializing the models.
$scope.category = {};
$scope.category.specs = [];
Next we ready the data to be used in the form (actually retrieved from the server via $http). We also initialize a variable to the first element in the categories array.
$scope.categories = [
{ "id": "1", "name": "mobile", specs: [
{ "id": "1", "label": "Operating System" },
{ "id": "2", "label": "Camera type" } ] },
{ "id": "2", "name": "laptop", specs: [
{ "id": "1", "label": "Operating System" },
{ "id": "2", "label": "Graphics Card" } ] }
};
$scope.selectedCategory = $scope.categories[0];
In the form, we have a dropdown which when selected loads the appropriate input fields specific to that category. We use the ngRepeat directive to accomplish this. This is a dynamic list of fields based on $scope.categories.specs. (please note the ???)
<select ng-model="selectedCategory" ng-options="category.name for category in categories"></select>
<div ng-repeat="spec in selectedCategory.specs">
<label>{{spec.label}}</label>
<input type="text" ng-model="???">
</div>
Ultimately, when the user clicks the submit button, we would like to extract the category he/she has selected and then package it together with the specifications they have filled in. The post request should contain something like the following for instance (of course, I only included one spec item, but in reality there would be many):
{ "id": "1", specs [ { "id": "2", "details": "RADEON HD 8970M" } ] }
Unfortunately I am not really sure how to accomplish this. I need to somehow create an array for the spec model, and then ensure that both the ID and user entered data are appropriately extracted... what goes in the ??? and what do we do after? Any help would be much appreciated.
this is how I do it. I make a form, validate it with angular, and then when its valid I submit it with a function.
<form name="signup_form" novalidate ng-submit="signupForm()"></form>
$scope.signupForm = function() {
var data = $scope.signup;
$http({
method : 'POST',
url : 'http://yoursite.com/mail.php',
data : $.param(data), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
});
}
also if you want to look at another form validation system for angular check out http://nimbly.github.io/angular-formly/#!/ It may help you solve your current form system.
In the controller, initialize $scope.specDetails as follows:
$scope.specDetails = {};
angular.forEach($scope.categories, function (category, index1) {
$scope.specDetails[category.id] = {};
angular.forEach(category.specs, function (spec, index2) {
$scope.specDetails[category.id][spec.id] = '';
});
});
In the html, replace "???" with specDetails[selectedCategory.id][spec.id]

AngularJS ng-repeat - http.gs retrieving data, but not displaying

I am new to angular and trying to integrate it within my application. I am attempting to use a simple $http.get to a .JSON file, which displaying the matching contents in a ng-repeat
Here my get:
$scope.countries = [];
$http.get('/resources/data/countries-report.json').success(function(data) {
$scope.countries = data.countries;
// alert(JSON.stringify($scope.countries));
console.log(data.countries);
console.log(data.countries.population);
}).error(function(error) {
alert('error');
});
Here's my .JSON file:
{
"firstName" : "Joe",
"surName" : "Bloggs",
"countries" : [
{ "name": "France", "population": "63.1" },
{ "name": "Span", "population": "52.3" },
{ "name": "United Kingdom", "population": "61.8" }
]
}
Here is my HTML:
<li ng-repeat="country in countries">
{{country.name}} has population of {{country.population}}
</li>
When viewing in the browser, all that is displayed is:
has population of
has population of
has population of
It seems as though my code can see there are 3 countries, as when i add or remove from my .JSON file, the list in the HTML modifies accordingly, however, the contents of the .JSON is not displaying.
Have i forgot to return the data from my .get??
** UPDATE *************************
As some have mentioned, my code seems to be correct, i think i know what the problem may be.
My application makes use of a HTML templating structure using Swig which accesses .JSON file using {{ }}.. Could this be causing confusion with Angular?
** UPDATE *************************
If i change:
var app = angular.module("app", []);
to
var app = angular.module('app', []).config(function($interpolateProvider){
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
}
);
And:
<li ng-repeat="country in countries">
{{country.name}} has population of {{country.population}}
</li>
To:
<li ng-repeat="country in countries">
{[{country.name}]} has population of {[{country.population}]}
</li>
Then the correct values are displayed.
you have to get the data in the array of object form like
[
{
id:1,
ima:gh.jpg,
data:
[
{
anotherid:1,
my:w,
ki:y
}
]
},
{
id=2,
ima:jh.jpg
}
]

Parsing JSON file with AngualrJS

I'm learning AngularJS and running some tests, but I'm having the following problem: I'm trying to read a JSON file, parse it into an object and show its properties on the screen. I read that $http parse the JSON text automatically, so I wrote the following code:
$http.get("/people").success(
function(data, status, headers, config) {
$scope.data = data.people;
}
);
This is my JSON file:
{ "people": [
{
"id": "0",
"name": "Cave Jhonson",
"company": "Aperture Science"
},
{
"id": "1",
"name": "Gustavo Fring",
"company": "Los Pollos Hermanos"
}
]
}
Which is in my project folder. I'm running a Python server. Finally, I'm trying to show the information with a simple HTML:
<p>{{data.people[0].name}}</p>
But when I open the page in Firefox the information doesn't show up and I get this error message: " Error: JSON.parse: expected property name or '}' "
My JSON is valid, so I can't understand why $http is not parsing it.
this line is inccorrect: <p>{{data.people[0].name}}</p>
You already put the code on scope in data so use that
<p>{{data[0].name}}</p>
Or you can use ng-repeat to show all the records like this
<div ng-repeat='item in data'>
<p>Id: {{item.id}}, Name: {{item.name}}, company: {{item.company}}</p>
<div>

Categories