Angularjs issue $http.get not loading image - javascript

I'm trying to create an ionic application which uses a gallery. I'm unsure why my image isn't being loaded into the application.
What i'm trying to develop is an gallery which loads the images from a JSON file.
Here's my HTML
<ion-view view-title="Gallery" align-title="center">
<ion-content ng-controller="photoCtrl" ng-init="getImages()">
<div class="row" ng-repeat="image in images" ng-if="$index % 4 === 0">
<div class="col col-25" ng-if="$index < images.length">
<img ng-src="{{data.images[$index].src}}" width="100%" />
</div>
<div class="col col-25" ng-if="$index + 1 < images.length">
<img ng-src="{{data.images[$index + 1].src}}" width="100%" />
</div>
<div class="col col-25" ng-if="$index + 2 < images.length">
<img ng-src="{{data.images[$index + 2].src}}" width="100%" />
</div>
<div class="col col-25" ng-if="$index + 3 < images.length">
<img ng-src="{{data.images[$index + 3].src}}" width="100%" />
</div>
</div>
</ion-content>
</ion-view>
Javascript:
.controller("photoCtrl", function($scope, $http) {
$scope.images = [];
$scope.getImages = function() {
$http.get('https://api.myjson.com/bins/30vuu')
.success(function(data) {
$scope.data = images;
})
}
});
I have also created a codepen: http://codepen.io/beefman/pen/eNMgzG

The JSON API return an associative array (key-value pair) like this:
{"images":"http://mintywhite.com/wp-content/uploads/2012/10/fond-ecran-wallpaper-image-arriere-plan-hd-29-HD.jpg"}
but your template code expects an array (list):
data.images[$index].src
so I would start by matching your JSON with the format expected by your template.
Edit: Here's a JSON format that would match your template's expectations:
{'images': [{'src': 'url1'}, {'src': 'url2'}]}
Also, make sure to set the images variable properly in your callback
$scope.images = data.images
now $scope.images is a list of key value pairs
with ng-repeat you can display the images like so:
<div ng-repeat="image in images">
<img ng-src="image.src" />
</div>

Your controller should be like this
.controller("photoCtrl", function($scope, $http) {
$scope.images = [];
$scope.getImages = function() {
$http.get('https://api.myjson.com/bins/30vuu')
.success(function(data) {
$scope.images = data;
})
}
});

Related

nested ng-repeat with json and rest api call back

I am trying to make a UI using list of product in a json(products.json) file on local and their availability in number from wp rest api call back in html(ionic) I have this:
Controller:
.controller('ShopCtrl', function($scope, $ionicActionSheet, BackendService, CartService, $http, $sce ) {
$scope.siteCategories = [];
$scope.cart = CartService.loadCart();
$scope.doRefresh = function(){
BackendService.getProducts()
.success(function(newItems) {
$scope.products = newItems;
console.log($scope.products);
})
.finally(function() {
// Stop the ion-refresher from spinning (not needed in this view)
$scope.$broadcast('scroll.refreshComplete');
});
};
$http.get("http://example.com/wp-json/wp/v2/categories/").then(
function(returnedData){
$scope.siteCategories = returnedData.data;
console.log($scope.siteCategories);
}, function(err){
console.log(err);
});
Template view:
<div ng-repeat = "product in products">
<div class="item item-image" style="position:relative;">
<img ng-src="{{product.image}}">
<div ng-repeat = "siteCategory in siteCategories">-->
<button class="button button-positive product-price" ng-click="addProduct(product)">
<p class="white-color product-price-price">post <b>{{siteCategory[$index].count}}</b></p>
</button>
</div>
</div>
<div class="item ui-gradient-deepblue">
<h2 class="title white-color sans-pro-light">{{product.title}} </h2>
</div>
<div class="item item-body">
{{product.description}}
</div>
</div>
so how can I achieve that? I tried to use nested ng-repeat but it didn't work out.

Ionic: Why are my images not loading from my json file?

I'm trying to load images from my json file into my application but i cannot get it to work:
Here's my code:
js:
.controller('photoCtrl', function($scope, $ionicModal, $ionicBackdrop, $ionicScrollDelegate, $ionicSlideBoxDelegate, $http) {
$scope.images = [];
$scope.getImages = function() {
$http.get('https://api.myjson.com/bins/37ia6')
.success(function(data) {
$scope.images = data.images;
})
}
html:
<ion-view view-title="Gallery" align-title="center" ng-controller="photoCtrl" >
<ion-content ng-init="getImages()" class="center" class="has-header padding">
<!-- start Under6/7/8/9s Photos -->
<div class="item item-divider">
<i class="ion-images"></i> Under6/7/8/9s Photos
</div>
<a class="item item-list-detail">
<ion-scroll direction="x">
<img on-hold="onHold()" ng-repeat="image in images" ng-src="{{images.src}}" ng-click="showImages($index)" class="image-list-thumb" />
</ion-scroll>
</a>
</ion-content>
</ion-view>
I think the reason is in your JSON. What would you expect to happen when iterating over:
{"images":"http://cdn.caughtoffside.com/wp-content/uploads/2012/07/Marko-Marin.jpg"}
Probably your API should return an array of objects like
[{"src":"http://cdn.caughtoffside.com/.../Marko-Marin.jpg"},
{"src":"http://cdn.caughtoffside.com/.../Johnny-Blue.jpg"},
...
]
Iterating over an object usually looks different:
<div ng-repeat="(key, value) in myObj">
Try this:
<ion-scroll direction="x" ng-repeat="image in images">
<img on-hold="onHold()" ng-src="{{image.src}}" ng-click="showImages($index)" class="image-list-thumb" />
</ion-scroll>

HTTP.GET isn't working

I'm trying to load a image from a HTTP.GET into my application. I'm unsure why the picture isn't loading.
Here is my code:
Html:
<ion-view view-title="Gallery" align-title="center" ng-controller="photoCtrl">
<ion-content class="center" ng-init="getImages()">
<div class="item item-divider">
<i class="ion-images"></i> Under6/7/8/9s Photos
</div>
<a class="item item-list-detail">
<ion-scroll direction="x">
<img on-hold="onHold()" ng-repeat="image in images" ng-src="images" ng-click="showImages($index)" class="image-list-thumb" />
</ion-scroll>
</a>
</ion-content>
</ion-view>
Javascript:
.controller("photoCtrl", function($scope, $http) {
$scope.data = [];
$scope.getImages = function() {
$http.get('https://api.myjson.com/bins/1jovy')
.success(function(data) {
$scope.data = data;
})
}
});
Add your photoCtrl controller to your view
I saw ng-repeat="data in data", here item and collection is having same name, which is not a good practice....
If I am rewiting this as ng-repeat="img in data" then your ng-src will be like
ng-src="{{img}}"
updated CODEPEN

Angularjs issue $http.get not working

I'm creating a mobile application using the framework ionic which is built on AngularJS.
I'm trying to load an image into my application from a JSON file but I cannot get it to load correctly.
Could anybody help me out?
Here's my HTML:
<ion-view view-title="Gallery" align-title="center" ng-controller="photoCtrl" ng-init="getImages()">
<ion-content>
<div class="col col-25" ng-repeat="image in images">
<img ng-src="{{images}}" width="100%" />
</div>
</ion-content>
</ion-view>
Here's my javascript:
.controller("photoCtrl", function($scope, $http) {
$scope.data = [];
$scope.getImages = function() {
$http.get('https://api.myjson.com/bins/30vuu')
.success(function(data) {
$scope.data = data;
})
.error(function() {
alert("Not working");
});
};
});
There are several issues here. First, your API call returns an object with a single property called images (not an array). Second, you're not accessing it in your HTML because that would be {{ data.images }} since your $scope member is called data.
So, the first thing you need to do is have the API return an array. If you do that, then use this HTML:
<ion-view view-title="Gallery" align-title="center" ng-controller="photoCtrl" ng-init="getImages()">
<ion-content>
<div class="col col-25" ng-repeat="image in data.images">
<img ng-src="{{image}}" width="100%" />
</div>
</ion-content>
</ion-view>
And this JavaScript:
.controller("photoCtrl", function($scope, $http) {
$scope.getImages = function() {
$http.get('https://api.myjson.com/bins/30vuu')
.success(function(data) {
$scope.data = data;
})
.error(function() {
alert("Not working");
});
};
});
If you only want your API to return one image then it's as simple as this for the HTML:
<ion-view view-title="Gallery" align-title="center" ng-controller="photoCtrl" ng-init="getImages()">
<ion-content>
<div class="col col-25">
<img ng-src="{{ data.images }}" width="100%" />
<!-- data.images because that's the name returned by the API call -->
</div>
</ion-content>
</ion-view>
The JavaScript doesn't need to change from what I have above;
Please change
<img ng-src="{{image}}" width="100%" />
instead of
ng-src="{{images}}"

angular js adding a class to an image in a gallery on click

I have an image gallery in angular js which multiple images. When a user clicks an image I want to add a style (in this case a border). If the clicks one of the selected images again, i want to remove the border. I have it working to add/remove imageURLs to an array of "selected_images" on click but I can't get the styles to add/remove.
Here is my markup:
<div class="col-md-3 col-sm-4 col-xs-6" ng-repeat="imageURL in property.imageURLs">
<img src={{imageURL}} ng-click="select_image(imageURL)" class="img-responsive" ng-class="{ 'selected-image': image_is_selected(image) }" style="max-height: 120px;" alt="" title="">
</div>
And the js:
$scope.image_is_selected = function(image) {
if($scope.selected_images.indexOf(image) == -1) {
return false;
} else {
return true;
}
}
$scope.select_image = function(image) {
console.log('image: ' + image);
var image_index = $scope.selected_images.indexOf(image)
console.log('image index: ' + image_index);
if(image_index != -1) {
$scope.selected_images.splice(image_index, 1);
} else {
$scope.selected_images.push(image);
}
}
This obviously isn't working as image_is_selected gets called a bunch of times... What is the best practice here?
You can simplify things by toggling a property on each image using ng-click:
<div class="col-md-3 col-sm-4 col-xs-6" ng-repeat="image in property.images">
<img src={{image.URL}}
ng-click="image.selected = !image.selected"
...
Then ng-class is simply:
ng-class="{ 'selected-image': image.selected }"
If you want to try the code for yourself, here it is on Plunkr.
To keep your existing data structure, you could populate an object on the fly with the selected property of each image:
<div class="col-md-3 col-sm-4 col-xs-6" ng-repeat="image in property.imageURLs">
<img src={{image}}
ng-click="selected_images[image] = {selected: !selected_images[image].selected }"
ng-class="{ 'selected-image': selected_images[image].selected }"
But this requires creating the selected_images ahead of time:
$scope.selected_images = {};
http://plnkr.co/edit/O3MUv0aT81O1PaEnRbQv?p=preview
Try this it me be help you
ng-click on Image add class and again click on image remove class
Here is Html file
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="image in images">
<img src={{image.img}} ng-click="selectImage($index)" ng-class="{ 'selected-image': $index === selectIdx }" >
</div>
</body>
</html>
Here is Controller
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.images = [
{img: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSHIwFa7lBRjCtY5K2WLGRuJ5XcXOwTUdgPPE1JKJHWEaoaG0Yh'},
{img: 'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTOAn_TGFgVS9CIW0y1hJ3deENr6KJx0AWP6W8FPvNDRcO-K5MyXg'},
{img: 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcR0In9KzRbpbnrVC5U1URXjHuQoTVhDjuemydVBzgJbPogvqaHa'}
]
$scope.selectIdx = -1;
$scope.selectImage = function ( $index ) {
if($scope.selectIdx === $index) {
$scope.selectIdx = -1;
} else {
$scope.selectIdx = $index;
}
}
});
Here is Css File
.selected-image {
border: 5px solid black;
}
Plunker Link
http://plnkr.co/edit/tm3rpkiKMBxhX98yr0IX?p=preview
There are many ways of achieving your required outcome. I'll try to explain one of them which I think would be best suited for your requirements. Keep in mind that when using ng-repeat you already have a reference to "$index" and that you can pass it direct into whatever expression you might have inside ng-click. Here's an solution:
HTML:
<div class="col-md-3 col-sm-4 col-xs-6"
ng-repeat="imageURL in property.imageURLs">
<img src={{imageURL}}
ng-click="select_image($index)"
class="img-responsive"
ng-class="{ 'selected-image': $index === selectedImageIndex }"
style="max-height: 120px;" alt="" title="">
</div>
Code:
$scope.selectedImageIndex = -1;
$scope.select_image = function ( $index ) {
$scope.selectedImageIndex = $index;
}
If you don't want to change the structure of your property.imageURLs variable into an array of objects then I think it would be better to create another variable $scope.selected = [] to store the boolean value to determine the selection of each image by index.
Example
HTML
<div class="gallery">
<img ng-repeat="url in imageUrls track by $index" ng-src="{{url}}" ng-class="{'selected-image': selected[$index]}" ng-click="selected[$index] = !selected[$index]" />
</div>
JAVASCRIPT
$scope.selected = []
And if you're ready to save these selected items and store them in an array, you can append this in your controller
JAVASCRIPT
$scope.save = function() {
var selectedImages = []
angular.forEach($scope.selected, function(isSelected, index) {
if(isSelected)
selectedImages.push($scope.imageUrls[index])
})
// Save your images
console.log(selectedImages)
}
See the associated plunker of the example above.
Note: As you can see that I've used the track by $index ng-repeat, this is to ensure that even if there are multiple images with the same urls, it does not throw a duplication error.
Try this
<div class="col-md-3 col-sm-4 col-xs-6" ng-repeat="imageURL in property.imageURLs">
<img src={{imageURL}} ng-click="select_image(imageURL)" class="img-responsive" ng-class="{active: isActive(imageURL)}" style="max-height: 120px;" alt="" title="">
</div>
Now in your controller
$scope.select= function(item) {
$scope.selected = item;
};
$scope.isActive = function(item) {
return $scope.selected === item;
};
.active class will be added to the selected image .
You can add styles to active class
More Info

Categories