Not retrieve image from JSON in Mobile Angular Ui.(Angular Js) - javascript

I want to retrieve image from JSON. Right now i am retrieving all these things from JSON Like Price, Display order But Image can't be retrieve.
HTML:
<div ng-controller="chooseProductDescription">
<div ng-repeat="cat in productDescription">
<img src="{{cat.product.productPictures[0].pictureUrl}}">
<span>Price</span>{{cat.product.price}}
<span>Display Order</span>{{cat.product.productPictures[0].displayOrder}}
</div>
</div>
CONTROLLER:
.controller('chooseProductDescription', function($scope, $http){
$http({
method:'get',
url:'http://www.json-generator.com/api/json/get/cgrvadFrGW?indent=2',
header:{'Content-Type':'application/json'},
}).success(function(data,status,headers, config){
$scope.productDescription = data;
alert("shjkshjksadhkjas");
}).error(function(data, status,headers, config){
})
})
Right now i am retrieving data from this URL:
http://www.json-generator.com/api/json/get/cgrvadFrGW?indent=2
i want to retrieve image from json. Please share your ideas.

You are not using the correct format in the reponse of the $http promise. The code should be :
$http({
method:'get',
url:'http://www.json-generator.com/api/json/get/cgrvadFrGW?indent=2',
header:{'Content-Type':'application/json'},
}).success(function(response){
$scope.productDescription = response.data;
alert("shjkshjksadhkjas");
}).error(function(response){
})

Related

Angularjs $scope.data not showing in html

I get the response from POST, it prints the data in the console but it doesn't show the data in the html page.
I have my controller, its just that the {{user}} doesnt show in html page
I can see the what it returns in the console,
angular.module('app.AllUsersCtrl', [])
.controller('AllUsersCtrl', function ($scope, $http, $cookies, $window, $state) {
$scope.getAccount = function (n) {
$http({
method: 'POST',
url: '/FYPapp/getAccount',
data: $.param({
username: n
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
}).success(function (data, status, headers, config) {
console.log(JSON.stringify(data));
$scope.user = JSON.stringify(data);
});
};
});
**Data Returns **
scripts.js:95 {"id":118,"firstname":"Lauren","lastname":"Smithss","description":"the Makup Chair the.....","enabled":true,"user":{"userid":21,"username":"theMak","email":"theMak22#mail.com","password":"995bf49114defd4f35d10e477135b89112ecdc2f25af6ab7969112842919ba4dc193b194f9485671","enabled":true},"followers":[],"username":"theMak"}
HTML: This is the html page
<link rel="stylesheet" type="text/css" href="static/app/css/css.scss">
<div class="mainDiv">
<h1> Profile Details</h1>
{{user}}
</div>
In your HTML you need to define our controller with ng-controller and also the ng-app which will be your module name.
Then you will need to make the data call.
After that you can directly assign the data to scope like this:
$scope.user = data;
As it appears you're using a controller alias, ie
.state('profile', {
url: "/profile",
templateUrl: '/views/profile.html',
controller: 'AllUsersCtrl',
controllerAs: 'allusers' // this one here
})
You should be assigning methods and properties to the controller instance, eg
.controller('AllUsersCtrl', ['$http', function($http) {
var ctrl = this;
this.getAccount = function(n) {
$http(...).then(function(response) {
ctrl.user = response.data;
});
};
}])
and in your template...
<img ng-click="allusers.getAccount(something)"...
and
<h1>Profile Details</h1>
<!-- for debugging -->
<pre>{{allusers.user | json}}</pre>
<!-- or for prod -->
<p>{{allusers.user.firstname}} {{allusers.user.lastname}}</p>
You are missing ng-controller in your html templates.
<h1> Profile Details</h1>
{{user}}

How to POST data to php template in angular

New to angular, new to php, new to programming at all.
I'm using ui-router, and here's how it looks like:
.state('admin', {
url:'/admin',
templateUrl: 'admin/admin.php',
controller: 'AdminController'
})
.state('admin.auto', {
url: '/auto',
templateUrl: 'admin/states/auto.php',
controller: 'AdminAutoController'
})
.state('admin.auto.update', {
url: '/update',
templateUrl: 'admin/states/autoupdate.php',
controller: 'AdminAutoUpdateController'
})
Routing works fine, on my admin.auto view, I've got list of autos with "edit" and "delete" buttons. I get the list from MySQL database.
<div ng-repeat="auto in autos">
<p>{{auto.mark}}</p>
<button class="btn btn-primary" ng-click="updateAuto(auto.mark)">Edit</button>
<button class="btn btn-danger">Delete</button>
</div>
So now I need to post auto.id to auto update nested view, so i can select proper table row. At this point I'm struggling to post any data to update view, just to find out if it works, so here it is:
.controller('AdminAutoController', ['$scope', '$http', '$modal', function($scope, $http, $modal) {
$http.get('php/DBZ.php').success(function(data) {
$scope.autos = data;
});
$http({
url: "admin/states/autoupdate.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({id:"some id"})
}).success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
}])
And, finally, my PHP:
<?php
$test = $_POST['id'];
echo $test;
?>
So, as a result, i get:
Notice: Undefined index: id on line 4
Sorry for my English, and thanks for any help!

Can't split up JSON

I am stuck with this annoying problem that I can't seem to figure out.
I want to take a JSON file and only show that information I find relevant. But somehow I can only show the whole thing, and not choose, for example, {{post.title}}.
Here is the JSON I want to use: http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json
This is my controller:
.controller('View5Ctrl', function ($scope, $http, $timeout)
$http({
method: 'GET',
//url: '/test/allMovies/test'
url: 'http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json',
dataType: 'json'
}).
success(function (data, status, headers, config) {
$scope.posts = data;
}).
error(function (data, status, headers, config) {
$scope.error = data;
});
});
And this is my HTML file
<div ng-repeat="post in posts" >
<div id="div">
<p>
{{post.title}}
</p>
<p></p>
</p>
</div>
By this, I only get a bunch of empty paragraphs. But if I remove the .title, I get the whole thing out.
SOLUTION:
Thanks for the answers! I will post the solution here for future viewers.
<div id="div">
<p>
{{posts.Title}}
</p>
</div>

AngularJs $scope doesn't update after a GET request on a factory

I have been trying AngularJS for a experimental project and I came along with this problem.
In my html I want to display a list of items
Index.html
<h1>Some list</h1>
<div ng-controller="datlist">
<div ng-repeat="item in items">
<div>Item description: {{item.description}}</div>
<div>Item name: {{item.name}}</div>
</div>
</div>
At first I was using a simple controller to get the information and update the view just using this:
controllers.js (original)
function datlist($scope,$http){
$http({method: 'GET', url: 'http://localhost:61686/getdatlist?format=json', headers: {'Access-Control-Allow-Origin': 'localhost:*'}}).
success(function(data, status, headers, config) {
$scope.items=data.itemsToReturn;
console.log(data);
}).
error(function(data, status, headers, config) {
console.log("fail");
});
}
This was working pretty well and I could get the list of items. Whilst, by changing my structure to use a factory to make the same request and bind it to $scope.items it doesn't work. I tried a lot of variations of $watch but I couldn't get it to update $scope.items. I found something about $apply but I really can't understand how to use it.
controllers.js (new one)
var datModule = angular.module('datModule',[]);
datModule.controller('datlist', function ($scope, datfactory){
$scope.items = datfactory.getlist();
$scope.$watch($scope.items, $scope.items = datfactory.getlist());
});
datModule.factory('datfactory', function ($http){
var factory = {};
factory.getlist = function(){
$http({method: 'GET', url: 'http://localhost:61686/getdatlist?format=json', headers: {'Access-Control-Allow-Origin': 'localhost:*'}}).
success(function(data, status, headers, config) {
console.log(data.itemsToReturn); //I get the correct items, all seems ok here
return data.itemsToReturn;
}).
error(function(data, status, headers, config) {
console.log("fail");
});
}
return factory;
});
Any ideas about this will be great.
PS: I found a lot of posts talking about this issue but none of them helped me to get a full solution.
Thanks
Using a watch for that is kinda ugly.
try this:
datModule.factory('datfactory', function ($http, $q){
this.getlist = function(){
return $http.get('http://localhost:61686/getdatlist?format=json',{'Access-Control-Allow-Origin': 'localhost:*'})
.then(function(response) {
console.log(response); //I get the correct items, all seems ok here
return response.data.itemsToReturn;
});
}
return this;
});
datModule.controller('datlist', function ($scope, datfactory){
datfactory.getlist()
.then(function(arrItems){
$scope.items = arrItems;
});
});
This is how you use promises for async matter.
UPDATE (15.01.2015): Now even sleeker!
The issue is nothing to do with the scope digest cycle. You are trying to return from inside a callback directly, which is not asynchronously possible.
I recommend you either use a promise, or return the http promise directly.
var factory = {};
factory.getlist = function(){
return $http({method: 'GET', url: 'http://localhost:61686/getdatlist?format=json', headers: {'Access-Control-Allow-Origin': 'localhost:*'}});
}
return factory;
To return the promise directly, and handle the success/fail at factory.getlist().success()
Alternatively, use your own promise if you want to wrap additional logic around the request.
var datModule = angular.module('datModule',[]);
datModule.controller('datlist', function ($scope, datfactory){
$scope.items = [];
datfactory.getlist().then(function(data) { $scope.items = data });
});
datModule.factory('datfactory', function ($http, $q){
var factory = {};
factory.getlist = function(){
var defer = $q.defer();
$http({method: 'GET', url: 'http://localhost:61686/getdatlist?format=json', headers: {'Access-Control-Allow-Origin': 'localhost:*'}}).
success(function(data) {
// alter data if needed
defer.resolve(data.itemsToReturn);
}).
error(function(data, status, headers, config) {
defer.reject();
});
return defer.promise;
}
return factory;
});
try to initialize $scope.items = []; at controller, before call $http
I hope it helps you.
Well it looks perfect but you can use $apply like this.
datModule.controller('datlist', function ($scope, datfactory){
$scope.$apply(function() {
$scope.items = datfactory.getlist();
});
});
I think another elegant solution to this problem could be - if you are using one of the routing libraries, in my case it is the UI-Router, but could be also ngRoute, is making your controller dependent on the response of the promise, eg. adding a resolve property to the adequate state/route which doesn't let the controller load until the promise is solved and the data is ready, so in your config:
.state('datpage', {
url: '/datpage',
controller: 'DatpageController',
resolve:{
datData: function (datfactory) {
return datDataService.getData("datDataParam");
}]
},
templateUrl: 'views/datpage.html'
})
And inject the datData dependency in your controller, where you can apply it directly to the $scope:
.controller('DatpageController', function ($scope,datData) {
$scope.datPageData = datData; ...

How to pass URL params in angular $http

I'm converting a server side CRUD app to Angular.js and have a small problem.
I'm getting my data with $http and display all the data via ng-repeat. I want to make users able to click and a specific item and redirect them to the resource.
So how can I pass a URL param to the $http get call dynamically?
Here's how I built the link to the resource (car.id = 3)
<a ng-href="/#/cars/{{car.id}}">Edit</a>
The link should go to http://local.dev/#/cars/3
So how do I bind the dynamic url in my controller?
Here's a stripped down version of my controller
App.controller('CarIndexCtrl', ['$scope', '$http', '$location', function ($scope, $http, $location) {
$scope.car = {};
$http({
method: 'GET',
url: $location.$$url,
})
.success(function (data, status, headers, config) {
$scope.car = data;
})
.error(function (data, status, headers, config) {
// error
});
}]);
So I'm interested to bind the URL the angular way. The above solution works, but feels very much like a hack. I'm not that familiar with Angular, so I like to stick to the defaults for now. I might consider restangular or ng-resource at a later time though...
the above solution works, but feels very much like a hack.
I don't think its hack or something messy.
I would generate URL list in controller (from my view its better for code maintenance) without appending in HTML. Something like:
$scope.urlList = [];
$http({
method: 'GET',
url: $location.$url,
})
.success(function (data, status, headers, config) {
$scope.car = data;
$scope.urlList.push("/#/cars/" + data.id);
})
.error(function (data, status, headers, config) {
// error
});
After in HTML:
<li ng-repeat="url in urlList" repeat-done="layoutDone()" ng-cloak>
<a ng-href="{{url}}">Edit</a>
</li>
BTW, I suggest you to use some loader because URL links we generate from promise (aka async) therefore with delay.
Demo Fiddle
In your app.js do something like this
var app = angular.module('YourAPP');
app.config(function ($routeProvider) {
$routeProvider
.when('/cars/:CarID', {
templateUrl: 'app/views/cars.html',
controller: 'CarIndexCtrl'
});
});
And in your controller
App.controller('CarIndexCtrl', ['$scope', '$http', '$location', '$routeParams', function ($scope, $http, $location, $routeParams) {
$scope.car = {};
$scope.carid = $routeParams.CarID;
$http({
method: 'GET',
url: $location.$$url,
})
.success(function (data, status, headers, config) {
$scope.car = data;
})
.error(function (data, status, headers, config) {
// error
});
}]);
And use the carid in wherever in your controller. Hope it helps.

Categories