I have this file api.php
require_once 'db.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$query=mysql_query("SELECT * FROM $tableName") or die(mysql_error());
$arr[];
while($obj = mysql_fetch_object($query)) {
array_push($arr, $obj);
}
echo $json_response = json_encode($arr);
It is grabbing all the data that i need.
Then i am trying to put that data into my $scope here...
// The controller
function InstantSearchController($scope, $http){
$http.get('api.php').success(function(data) {
$scope.items = data;
$scope.items = [
image : data['icon'],
english : data['english'],
british : data['british']
];
});
}
But this does work if I hard code the data like this.
function InstantSearchController($scope){
$scope.items = [
{
english: 'English A',
british: 'British A',
image: 'images/advil.jpg'
},
{
english: 'English B',
british: 'British B',
image: 'images/advil.jpg'
}
]
}
This is the error that i am seeing in the console
Uncaught SyntaxError: Unexpected token : js/angular.js:44
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.15/$injector/modulerr?p0=instantSearch&p1=E…larjs.org%2F1.2.15%2F%24injector%2Fnomod%3Fp0%3DinstantSearch%0A%20%20%20%......1)
This is the fiddle trying response #1
http://jsfiddle.net/XgsWU/
And this one is for response #2
http://jsfiddle.net/JGjyS/
To anyone that might be reading this later I figured out my issues was in my controller call and i have changed/updated to this and it is working great!
app.controller('InstantSearchController', ['$scope', '$http', function($scope, $http) {
$http.get('inc/api.php').success(function(itemData) {
$scope.items = itemData;
});
}]);
Unexpected token :. This is from:
$scope.items = [
image : data['icon'],
You should use $scope.items = {...} since you want a JavaScript object with key-value pairs, not an array.
It seems like you also want to loop over data and push items onto the array:
$scope.items = [];
data.forEach(function (datum) {
$scope.items.push({
image: datum.icon,
english: datum.english,
british: datbum.british,
});
});
You have a syntax error here:
$scope.items = [
image : data['icon'],
english : data['english'],
british : data['british']
];
It should be:
$scope.items = [
{image : data['icon'],
english : data['english'],
british : data['british']}
];
Related
I created a project that allows converting HTML to PDF. I'm using phantom-render-stream
to convert the HTML to PDF. My problem now, I failed to pass an object value to HTML. Below is my code.
app.js
var username = "AAA";
var pets = [
{id: 1, name: "cat"},
{id: 2, name: "dog"},
{id: 3, name: "sugar glider"}
];
var address = {
line1: "Street A123",
town: "Edinburgh",
country: "Scotland"
};
render('http://localhost:8888/createForm.html?username='+username+'&pets='+pets+'&address='+address
.pipe(fs.createWriteStream('customer.pdf'));
In createForm.html, I used an AngularJS to get and view the value to PDF.
createForm.html
<script>
var app = angular.module('myApp', []);
app.config(function($locationProvider){
$locationProvider.html5Mode(true);
});
app.controller('getDataCtrl', function($scope, $location) {
var url = decodeURIComponent( $location.url() );
var value = $location.search();
$scope.username = value.username;
$scope.pets = value.pets;
$scope.address = value.address;
})
</script>
<body>
<div ng-app="onePayForm" ng-controller="getDataCtrl">
<p>{{username}}</p>
<p>{{pets[0].name}}</p>
<p>{{address.line1}}</p>
</div>
</body>
After successfully converting HTML to PDF, I opened the pdf file to see the result. Only username appears in pdf, the rest shows like this {{pets[0].name}} {{address.line1}}.
in
render('http://localhost:8888/createForm.htmlusername='+username+'&pets='+pets+'&address='+address)
.pipe(fs.createWriteStream('customer.pdf'));
your query params need to be prepared before appending them to the url. What you should do
var readyPets = encodeURIComponent(JSON.stringify(pets));
var readyAddress = encodeURIComponent(JSON.stringify(address));
then change the code above to :
render('http://localhost:8888/createForm.htmlusername='+username+'&pets='+readyPets+'&address='+readyAddress)
.pipe(fs.createWriteStream('customer.pdf'));
in createForm.html parse these param queries:
$scope.pets = JSON.parse(decodeURIComponent(value.pets));
$scope.address = JSON.parse(decodeURIComponent(value.address));
I am a newbie to IonicFrameWork and was following their "starter tab" template and made a few modifications to "delete" and "bookmark" items from a factory.
My books.js which contains the factory looks as follow:
.factory('Books', function() {
// books data
var books = [{
id: 0,
title: 'Sample Title',
author: 'Sample Author',
category: 'Horor, Fiction',
cover: '/cover.jpeg',
details: 'some details about the book',
chapters: [
{
id : 1,
name: 'Chapter 1',
filename: 'chapter1.html',
},
{
id : 2,
name: 'Chapter 2',
filename: 'Chapter2.html',
}
]
}
.....
return {
all: function() {
return books;
},
// remove a book from the list
remove: function(book) {
books.splice(books.indexOf(book), 1);
},
and my controllers.js looks like this:
....
.controller('DashCtrl', function($scope, Books) {
$scope.books = Books.all();
$scope.remove = function(book) {
Books.remove(book);
};
})
.controller('singlebookCtrl', function($scope, $stateParams, Books){
$scope.book = Books.get($stateParams.bookId);
$scope.toggleIcon = function ($evemt, iconName, book){
var buttonClasses = $event.currentTarget.className;
// add the book to favorite
if (....){
book.isFavorite = true;
}
// remove the book from favorite
else {
book.isFavorite = false;
}
....
when I exit the app and open it again, the deleted item is back and favorite items are gone.
When searching for a solution , I came across this article which states I should use window.localstorage. But not sure how I should apply this method for a factory.
I personnaly prefer using ngStorage that makes it very simple and straight forward to use localStorage & sessionStorage.
For example, after injecting the dependency in your controller you can:
Set a variable :
$scope.favList = [1, 4, ...]
$scope.jsonList = { ... }
$localStorage.favLists = $scope.favList;
$localStorage.jsonList = $scope.jsonList;
Access a variable, Simply access to localStorage value :
var favList = $localStorage.favLists;
For all intents and purposes you can treat Local Storage just as if it were a key/value store, like a javascript object. So if you want to save a value in local storage, just do it like the following.
window.localStorage["bookOne"] = "STRING HERE"
Or if you want to save a javascript object:
window.localStorage["bookOne"] = JSON.stringify({a:b})
And it should persist between page reloads.
The real issue here is that in your code, you are setting books on each load with var books = .... Every time you reload the application it will re-apply books and favourites will be lost. So beyond just saving it to window.localStorage you will also have to read from local storage and assign it to your books and favourites variables when your app loads in order to see the changes that were previously made.
You can simply do it with angular-local-storage module, here's some example based on your problem.
angular.module('app', ['LocalStorageModule'])
.factory('Books', function(localStorageService) {
// favorites list(books id)
var favList = [1, 2, 3, ...];
// ....
return {
remove: function(id) {
favList.splice(favList.indexOf(id), 1);
// sync with localStorage
localStorageService.set(favorites, favList);
},
// ....
}
});
Note that you can simply use angular-local-storage#bind and bind specific scope-key to this service that automatically do this synchronisation for you. for example:
// Inside your controller
$scope.favList = [1, 4, ...]
// returns a deregistration function for this listener.
$scope.unbind = localStorageService.bind($scope, 'favList');
I'm new to AngularJS for a project and I'm trying to extract a json array from a http response to use in a list.
The response looks like this:
{
"DFH0XCMNOperationResponse": {
"ca_return_code": 0,
"ca_inquire_request": {
"ca_last_item_ref": 150,
"ca_item_count": 15,
"ca_cat_item": [
{
"ca_cost": "002.90",
"in_stock": 119,
"ca_description": "Ball Pens Black 24pk",
"on_order": 0,
"ca_department": 10,
"ca_item_ref": 10
},
{
"ca_cost": "002.90",
"in_stock": 6,
"ca_description": "Ball Pens Blue 24pk",
"on_order": 50,
"ca_department": 10,
"ca_item_ref": 20
}
],
"ca_list_start_ref": 0
},
"ca_response_message": "+15 ITEMS RETURNED",
"ca_request_id": "01INQC"
}
}
The code for the resource and request looks like this:
.factory('getCatalog', ['$resource', function($resource){
return $resource('catalogmanagertest/v1/apps/bca45894-92f7-49dc-ae54-b23b89ab6c73/catalog', {}, {query: {method:'POST'}});
}]);
And the controller code relevant looks like this:
angular
.module('catalogController', ['ngMaterial', 'ngResource'])
.controller('catalogController', ['$scope', 'getCatalog', 'catalog', function($scope, getCatalog, catalog) {
$scope.debug = getCatalog.query(); // set scope catalog to array from zOS
$scope.catalog = catalog.ca_cat_item;
$scope.message = "This is a test order message";
this.tiles = buildGridModel({
icon : "avatar:svg-",
title: "",
cost: "€",
background: "",
stock: ""
});
function buildGridModel(tileTmpl){
var it, results = [ ];
var tmp = $scope.debug.DFH0XCMNOperationResponse.ca_inquire_request.ca_cat_item;
console.log(tmp);
The next to last line is what I'm having trouble with. How do extract the expected array? I get the newbie error when I do the console.log:
TypeError: Cannot read property 'ca_inquire_request' of undefined
Replace
$scope.debug = getCatalog.query();
with
getCatalog.query().$promise.then(function (result) {
$scope.debug = result;
console.log($scope.debug.DFH0XCMNOperationResponse.ca_inquire_request.ca_cat_item);
});
Here You can see I just converted api call into the promise.In your code before console is logging variable before response come.
Hello I am developing an Ionic app and I have an array that I want to push items on to it, but not lose the data when I change screens. Also, I do not want to use a database. Is there any other way? to add to an existing array and store that array locally?
$scope.tasksCollection = [
{ info: 'Go studying', measured: 'no', total: 1, done: 1, id: 1 },
{ info: 'Go to the beach', measured: 'no', total: 1, done: 1, id: 2},
{ info: 'Run', measured: 'yes', total: 30, done: 15, id: 3}
];
$scope.tasksCollection.push({
info: $scope.taskInfo,
measured: $scope.result,
total: total,
done: 0,
id: $scope.tasksCollection.length
})
The add function is working perfectly I just loose the data when changing states.
If you want to keep data between controllers either use a service or local storage if you want to keep the data even when you quit the app.
Service example
Further angular documentation regarding services: https://docs.angularjs.org/guide/services
service.js:
angular.module('yourmodule.services')
.service('Tasks', [function () {
var collection = {
tasks: []
};
return {
getTasks : function(){ return collection.tasks; }
}
}]
);
controller.js
angular.module('yourmodule.controllers')
.controller('TaskCtrl', ['$scope', 'Tasks',
function($scope, Tasks){
$scope.Tasks = Tasks //Expose service to template
$scope.addTask = function(){
Tasks.getTasks().push({name : 'a new task'});
}
}]);
Local storage example
This is an excellent library which provides easy localstorage access for angularjs: https://github.com/grevory/angular-local-storage
angular.module('yourmodule.controllers')
.controller('TaskCtrl', ['$scope', 'localStorageService',
function($scope, localStorageService){
$scope.collection = {
tasks : localStorageService.get('tasks') || [];
}
$scope.addTask = function(){
$scope.collection.tasks.push({name : 'a new task'});
localStorageService.set('tasks', $scope.collection.tasks);
}
}]);
How about HTML5's locaStorage?
See Ionic formulas on Using Local Storage.
I've been working on the CodeSchool AngularJS app, which I've understand so far, but when I began using dependency injections, specifically, $http in order to make an call for my JSON data the app stops working, and I don't know why. Originally with the first line uncommented the app worked as it should using the variable gems declared within the closure, which is exactly the same code now found in products.json. I commented out the first line of the controller, and added the appropriate changes to for dependency injection, but now the app doesn't load at all, and it throws the error found below (also see $http-injection.png).
app.controller('StoreController', [ '$http', function($http) {
//this.products = gems; <-- works like this with data in closure
var store = this;
store.products = [ ]; // no erros on page load
$http.get('/data/products.json').success(function( data ) {
store.products = data;
});
}]);
Error: [ngRepeat:dupes] http://errors.angularjs.org/1.3.0-beta.10/ngRepeat/dupes?p0=product%20in%20storeCtrl.products&p1=string%3A%0D
at Error (native)
at http://angularjs.dev/angular-1.3/angular.min.js:6:457
at http://angularjs.dev/angular-1.3/angular.min.js:204:24
at Object.<anonymous> (http://angularjs.dev/angular-1.3/angular.min.js:108:144)
at Object.applyFunction [as fn] (<anonymous>:778:50)
at g.$digest (http://angularjs.dev/angular-1.3/angular.min.js:109:211)
at g.$delegate.__proto__.$digest (<anonymous>:844:31)
at g.$apply (http://angularjs.dev/angular-1.3/angular.min.js:112:325)
at g.$delegate.__proto__.$apply (<anonymous>:855:30)
at g (http://angularjs.dev/angular-1.3/angular.min.js:73:287) angular.js:10811
(anonymous function) angular.js:10811
(anonymous function) angular.js:7962
g.$digest angular.js:12560
$delegate.__proto__.$digest VM8634:844
g.$apply angular.js:12858
$delegate.__proto__.$apply VM8634:855
g angular.js:7380
x angular.js:8527
y.onreadystatechange
product.json
[
{
name: 'Hexagonal',
price: 250.00,
description: 'The six faces of the hexaonal gem have a habit to excite the eye, and attract good luck.',
canPurchase: true,
soldOut: false,
images: [ ],
reviews: [
{
stars: 5,
body: "I love this product!",
author: "mtpultz#gmail.com"
},
{
stars: 1,
body: "This product sucks!",
author: "mtpultz#hater.com"
}
]
},
{
name: 'Dodecahedron',
price: 1015.25,
description: 'Some gems have hidden qualities beyond their luster, beyond their shine... Dodeca is one of those gems.',
canPurchase: true,
soldOut: false,
images: [
"img/gem-06.gif",
"img/gem-02.gif",
"img/gem-01.gif"
],
reviews: [
{
stars: 3,
body: "I think this gem was just OK, could honestly use more shine, IMO.",
author: "mtpultz#hotmail.com"
},
{
stars: 4,
body: "Any gem with 12 faces is for me!",
author: "mtpultz#casensitive.ca"
}
]
},
{
name: 'Pentagonal Gem',
price: 5.95,
description: 'Origin of the Pentagonal Gem is unknown, hence its low value. It has a very high shine and 12 sides however.',
canPurchase: true,
soldOut: false,
images: [
"img/gem-02.gif",
"img/gem-06.gif",
"img/gem-01.gif"
],
reviews: [
{
stars: 4,
body: "The mystery of the Pentagonal Gem makes it sooo fascinating!",
author: "mtpultz#peanutbutter.com"
},
{
stars: 5,
body: "I can't get enough of the five faces of the Pentagonal Gem!",
author: "mtpultz#ketchup.ca"
}
]
}
];
Originally I was going to try and figure out how to use $log as well, and when I had $log injected it appears as if the json is received (see $http-and-$log-injection.png attached) based on the chrome batarang plugin's output, but the app still doesn't work either way, only the JSON appears on right side of batarang output.
app.controller('StoreController', [ '$http', '$log', function($http, $log) {
//this.products = gems;
var store = this;
store.products = [ ]; // no erros on page load
$http.get('/data/products.json').success(function( data ) {
store.products = data;
});
}]);
You shouldn't use the minified version of Angular while developing. You'll get better error messages when using the non-minified version. But even when you're using the minified version you can get a pretty good idea of what the problem is by visiting the url mentioned first in the exception: http://errors.angularjs.org/1.3.0-beta.10/ngRepeat/dupes?p0=product%20in%20storeCtrl.products&p1=string%3A%0D
It seems like you have duplicates in products.json. Without seeing the whole contents of products.json or any of your markup that would be my best guess.
--
Update: It seems like data is a string and not an array. This is probably because the response body from the server is not properly formatted JSON. Instead of traversing objects in an array, ng-repeat traverses characters in a string and throws an error on the second tab character (encoded as %0D) it detects. I've created a plnkr with properly and a bad response as an example: http://plnkr.co/edit/XbPuXkykzv36NyH3sSeu?p=preview
You should use $scope:
$scope.store = {};
$scope.store.products = [ ]; // no erros on page load
$http.get('/data/products.json').success(function( data ) {
$scope.store.products = data;
});
ngRepeat:dupes error occurs if there are duplicate keys(values in your array/json) in an ng-repeat expression, this is because AngularJS uses keys to associate DOM node with ng-repeated items. The requested data products.json may have fields that contain the same value, to solve this, you can append a track by $index expression in your ng-repeat so that the association of DOM node items will be keyed by the index of the your array/json instead of the value of each item.
E.G.
<div ng-repeat="product in Store.products track by $index"></div>