i created my new store in angularjs. In there i have a function called store, where it gets all my products. In the start i just wrote all the products in there, but now i want to get them from a mysql database. I think that the problem is something in the $http.get, but dont know what.
Before my function looked like this:
function store() {
this.products = [
{ num: 1, code: 'TEST', category: 'Diverse', name: 'TEST', src: "test.png", description: 'info her', price: 2, cal: 10 }
];
}
Which worked. I created the code below, with the $http.get, and that code dont show anything in my store:
function store() {
$http.get('products.php')
.success(function(data) {
this.products = data;
});
}
My products.php file echo this and it does encode to json:
[{"num":"1","code":"TET","category":"Diverse","name":"Test","src":"test.png","description":"Test","price":"5","cal":"10"}]
products.php file:
require('scripts/connect.php');
$statement = $conn->prepare("select * from products");
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC)){
foreach($row as $key => $value) {
$prod[$key] = $value;
}
$main_arr[] = $prod;
}
$json = json_encode($main_arr);
echo $json;
Extra code for help:
controller.js
function storeController($scope, $routeParams, DataService) {
// get store and cart from service
$scope.store = DataService.store;
$scope.cart = DataService.cart;
}
app.js
storeApp.factory("DataService", function () {
// create store
var myStore = new store();
});
I really don't know how your code works, but you said that this code is working fine:
function store() {
this.products = [
{ num: 1, code: 'TEST', category: 'Diverse', name: 'TEST', src: "test.png", description: 'info her', price: 2, cal: 10 }
];
}
And I'm assuming you have an access to the $http
somehow.
To convert the above code to use the $http
, it should be like this instead:
function store() {
var self = this;
$http.get('products.php')
.success(function(data) {
self.products = data;
});
}
Hope this helps.
make sure you've properly injected the $http
module into your controller (or service, however you're going about it).
var myApp = angular.module('myApp',[]);
myApp.controller('storeController', ['$scope', '$http', function($scope, $http) {
$scope.store = {products: getData()};
function getData() {
$http.get('products.php')
.success(function(data) {
return data;
});
}
}]);
Are you getting any errors in the console?