ng-repeat not iterating through list of images in JSON - javascript

I'm quite new to Angular and am having trouble using the $http service to make a GET request for images in JSON (just a plain array of images). For every image, I want to repeat that and add them into my ng-src. I'm trying to achieve a layout similar to Instagram.
So I think the $http.get part is correct where I store it into $scope.imageUrls, and from there I iterate through it using ng-repeat. Then from there, for each iteration, I plug that into ng-src in my img tag and I just don't know how to debug from there.
HTML:
<div class="posts" ng-controller="PostController">
<div class="post" ng-repeat="imageUrl in imageUrls">
<img class="photo" ng-src="{{imageUrl}}" />
<div class="post-box">
<div><span class="likes"> # </span> Likes</div>
</div>
</div>
</div>
JS:
var app = angular.module('instagram', []);
app.controller('PostController', ['$scope', '$http', function($scope, $http) {
$http.get('https://codesmith-precourse.firebaseio.com/instagram/-JqL35o8u6t3dTQaFXSV.json')
.then(function (data) {
$scope.imageUrls = data;
console.log($scope.imageUrls);
});
}]);
I tried used console.log to check for errors, but the data seems to be there. Is it just returning the block of data rather than each element/image in the JSON?
Checking the console: console.log($scope.imageUrls)
I also tried using {{imageUrl.url}} as ng-src but that seemed to trigger errors as well. I set up a Plnkr:
http://plnkr.co/edit/yQpCIRp9FHdDHTMA1HCL?p=preview
This has been bugging me for awhile, so if you can help, thanks!

I update your plunker http://plnkr.co/edit/hNn1YdVh8w7l3dEgh3LU?p=preview:
In $http you get a responsa that contains more informations that only data. To get data you must do it :
$http.get('https://codesmith-precourse.firebaseio.com/instagram/-JqL35o8u6t3dTQaFXSV.json')
.then(function (response) {
$scope.imageUrls = response.data;
console.log($scope.imageUrls);
});
And in ng-repeat you must add track by argument because image can be duplicate

You are setting imageUrls to an object. It needs to be an array. If you look in the debugger your response is this:
You want whats in data.data (You also should define the imageUrls variable ($scope.imageUrls = []')
<!doctype html>
<html ng-app="instagram">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Angular</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="posts" ng-controller="PostController">
<div class="post" ng-repeat="imageUrl in imageUrls">
<img class="photo" ng-src="{{imageUrl}}" />
<div class="post-box">
<div><span class="likes"> # </span> Likes</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('instagram', []);
app.controller('PostController', ['$scope', '$http', function($scope, $http) {
$scope.imageUrls = [];
$http.get('https://codesmith-precourse.firebaseio.com/instagram/-JqL35o8u6t3dTQaFXSV.json')
.then(function (data) {
$scope.imageUrls = data.data;
});
}]);
</script>
</body>
</html>

updated plunkr http://plnkr.co/edit/agVrWD8I4581a0702ehy?p=preview
you have to get data.data
$http.get('https://codesmith-precourse.firebaseio.com/instagram/-JqL35o8u6t3dTQaFXSV.json')
.then(function (data) {
$scope.imageUrls = data.data;
});
and use track by $index in the ng-repeat because you have duplicate
<div class="posts" ng-controller="PostController">
<div class="post" ng-repeat="imageUrl in imageUrls track by $index">
<img class="photo" ng-src="{{imageUrl}}" />
<div class="post-box">
<div><span class="likes"> # </span> Likes</div>
</div>
</div>
</div>

First of all in $http method the response value is an object containing "data" element that is the data you need so use this :
$scope.imageUrls = data.data;
then you have duplicate image url , in this case ng-repeat returns an error so use this instead :
<div class="post" ng-repeat="imageUrl in imageUrls track by $index">

Related

how to get data in ng dialog angularjs using http method?

Getting Data from database with php. Data is fine. Butt data is not showing in NgModel box. I have passed scope parameter in ngdialog function. Please help me out.
var adminapp = angular.module("uibootstrap", ["ngRoute", 'ngDialog']);
adminapp.controller("homedata", function($scope, $rootScope, $http, $httpParamSerializerJQLike, ngDialog, $timeout) {
$rootScope.theme = 'ngdialog-theme-default';
$scope.openDefault = function() {
ngDialog.open({
template: 'firstDialogId',
className: 'ngdialog-theme-default',
scope: $scope
})
};
// get user
$http.get('http://localhost/database/get-user.php').success(function(response) {
$scope.users = response;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<li ng-repeat="item in users">
<a href="javascript:void(0);" ng-click="openDefault()">
<div class="img"><img alt="" src="admin/images/user-img2.jpg"> <span class="status-red"></span></div>
<div class="msginfo">
{{item.user_name}} <br> <span>{{item.user_status}}</span>
</div>
</a>
<script type="text/ng-template" id="firstDialogId">
<div class="ngdialog-message">
<div class="data">
<div class="img">
<img alt="" src="http://localhost/rockeditor/admin/images/img-user.png"> <a class="editbtn" href="#"><i class="fa fa-edit"></i></a>
</div>
<div class="name">{{item.user_name}}</div>
<span class="editor">{{item.user_status}}</span>
<span class="email">{{item.user_email}}</span>
<input class="btn-green" type="submit" value="Save">
</div>
</div>
</script>
</li>
variable item is not available in your template firstDialogId, actually it's not a child node of <li></li>
You forget to include controller in your html.
Use ng-controller="homedata" on <li> element
item is not accessible in that script tag
$scope.users is available after $http call returned with success response
See here
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="ngDialog.css" />
<link rel="stylesheet" href="ngDialog-theme-default.css" />
<script data-require="angular.js#*" data-semver="1.3.0" src="//code.angularjs.org/1.3.0/angular.js"></script>
<script src="ngDialog.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="MyApp" ng-controller="homedata">
<button ng-click="clickme()">Hello World</button>
<script type="text/ng-template" id="firstDialogId">
<div ng-repeat="user in users">
<div>Current user:</div>
<div>{{user.name}}</div>
</div>
</script>
</body>
</html>
script.js
// Code goes here
angular.module("MyApp", ['ngDialog'])
.controller("homedata", homedata)
function Main($scope, ngDialog) {
$scope.users = [
{name: 'abc'},
{name: 'xyz'}
];
$scope.clickme = function() {
ngDialog.open({
template: 'firstDialogId',
className: 'ngdialog-theme-default',
scope: $scope
});
};
}
But as per your controller, There is a $http call and until it responded you don't have any data in $scope.users. So, please make sure that it and you only get data in your dialog after the $http is get success response

Why doesn't angular load in this plnkr?

I have researched my issue and tried many solutions but have not solved it.
For some reason angular does not seem to be loading in plunker.
I have head iffy are no longer supported in later version in angular, but I have tried loading an older version and still does not work.
Any ideas on how I can get this running?
Here is the link:
http://plnkr.co/edit/rrnzNjze2QqkWtjvNUNH?p=preview
HTML
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script data-require="angular.js#*" data-semver="1.1.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.0/angular-bootstrap-prettify.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{message}}</h1>
<div>
{{ error }}
</div>
<div>
<div>
Name: {{user.name}}
</div>
<div>
Location: {{user.location}}
</div>
<div>
<img ng-src="{{user.avatar_url}}" title="{{user.name}}" />
</div>
</div>
</body>
</html>
Javascript
// Code goes here
var app = angular.module("githubViewer", []);
var MainController = function($scope, $http) {
var onUserComplete = function(response){
$scope.user = response.data;
};
var onError = function(reason){
$scope.error = "Could not fetch the user request!";
};
$http.get("https://api.github.com/users/robconery")
.then(onUserComplete, onError);
$scope.message = "Hello, Angular!";
};
app.controller("MainController", ["$scope", "$http", MainController]);
Replace angular-bootstrap-prettify.js (I don't know what is angular-bootstrap-prettify, do you really need it?) by angular.js and your plunkr works.

Editing JSON search results from within Angular

I am now pulling data from a external JSON URL properly to the master page, but my detail page doesn't seem to pass on the object initallt received from http.get. This master part of the app can be viewed in a Code Pen at CODEPEN
<label class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="search" ng-model="query" placeholder="Search Slugname">
<button class="button button-dark" ng-click="getOrders()">Submit</button>
</label>
If my user wanted to change the date(order.date)value manually to say "10/8/16". How can I access/edit any of the JSON values that are returned from the external API?
I eventually wish to edit the returned JSON data within my app and then post that revised data back to a PHP API server.
Your main issue is that you want to modify the incoming data from the $http call.
You can implement an http interceptor, the method response will take the response modify it and then return it to the caller. Since the http interceptor will take all the incoming requests just check the url start to not modify other requests.
angular.module('ionicApp', ['ionic'])
.factory('httpInterceptor', function($q, $rootScope) {
var httpInterceptor = {
response: function(response) {
var deferred = $q.defer();
var results = response.data;
var urlStart = 'http://mvcframe.com/wpapi/wp-json/wp/v2/pages?slug=';
if (response.config.url.startsWith(urlStart)) {
angular.forEach(results, function(result, key) {
result.date = '10/8/16';
});
}
deferred.resolve(response);
return deferred.promise;
}
};
return httpInterceptor;
})
.config(function($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
})
.controller('ListController',
['$scope', '$http', '$state', '$stateParams', '$window', '$location',
function($scope, $http, $state, $stateParams, $window, $location) {
$scope.getOrders = function(query) {
$http.get('http://mvcframe.com/wpapi/wp-json/wp/v2/pages?slug=' + query)
.success(function(data) {
$scope.orders = data;
})
}
$scope.orders = [];
}]);
The only modification that I've made on your html is to send query param directly to the function on the ng-click
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Tabs Example</title>
<link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
<script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
</head>
<body ng-controller="ListController">
<ion-header-bar class="bar-dark" align-title="center">
<h2 class="title">Order Search</h2>
</ion-header-bar>
<ion-content padding="true" class="has-header">
<div class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="text" ng-model="query" placeholder="Search Slugname">
<button type="submit" class="button button-dark" ng-click="getOrders(query)">Submit</button>
</div>
<p>An example and working slug search term is test-3. The JSON can be viewable in a browser using https://mvcframe.com/wpapi/wp-json/wp/v2/pages?slug=test-3</p>
<ion-list>
<ion-item ng-repeat="order in orders | filter:query" class="item-thumbnail-left item-text-wrap" href="#/tab/list/{{order.id}}">
<h2>Page ID: {{order.id}}</h2>
<h3>Date created: {{order.date}}</h3>
<h2>Page URL: £{{order.link}}</h2>
<h2>Page Title: £{{order.title/rendered}}</h2>
</ion-item>
</ion-list>
</ion-content>
</body>
</html>
I almost forgot the codepen is here: http://codepen.io/pachon1992/pen/QEodJR
EDIT ---------------------------
As per comments you want your user to update manually the data right? as an example you would like to update the date, you can do enabling a input for the user to edit the data, since angular is two-way data-binding will modify your data.
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Tabs Example</title>
<link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
<script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
</head>
<body ng-controller="ListController">
<ion-header-bar class="bar-dark" align-title="center">
<h2 class="title">Order Search</h2>
</ion-header-bar>
<ion-content padding="true" class="has-header">
<div class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="text" ng-model="query" placeholder="Search Slugname">
<button type="submit" class="button button-dark" ng-click="getOrders(query)">Submit</button>
</div>
<p>An example and working slug search term is test-3. The JSON can be viewable in a browser using https://mvcframe.com/wpapi/wp-json/wp/v2/pages?slug=test-3</p>
<ion-list>
<ion-item ng-repeat="order in orders | filter:query" class="item-thumbnail-left item-text-wrap" href="#/tab/list/{{order.id}}">
<h2>Page ID: {{order.id}}</h2>
<div><input type="text" ng-model="order.date"></div>
<h2>Page URL: £{{order.link}}</h2>
<h2>Page Title: £{{order.title/rendered}}</h2>
</ion-item>
<button type="button" class="button button-dark" ng-click="update()">Update</button>
</ion-list>
</ion-content>
</body>
</html>
In your controller you can call http service for every order calling via typically to a PUT endpoint
angular.module('ionicApp', ['ionic'])
.controller('ListController', ['$scope', '$http', '$state', '$stateParams', '$window', '$location',
function($scope, $http, $state, $stateParams, $window, $location) {
$scope.query = "";
$scope.getOrders = function(query) {
$http.get('http://mvcframe.com/wpapi/wp-json/wp/v2/pages?slug=' + query)
.success(function(data) {
$scope.orders = data;
});
}
$scope.orders = [];
$scope.update = function() {
angular.forEach($scope.orders, function(order) {
//whetever url you are using
$http.put('http://mvcframe.com/wpapi/wp-json/wp/v2/pages/update/' + order.id, order, {})
.success(function(data) {
console.log('updated');
});
});
};
}
]);
I've edited the codepen
https://codepen.io/anon/pen/qNLOAP
So apparently it seems you cannot have a button in a <label> with ng-click. I changed the label to a <div> and it started working.
The search doesn't work at the moment but that should get you going.
Please resolve listed points.
1> tabs.home state you don't have injected controller and the other thing is also define home.html and
2> all other template separably in templates folder parallel to your controllers.
3> http call to http://mvcframe.com/wpapi/wp-json/wp/v2/pages requires cross origin domain support for that you can use chrome (CORS) plugin.
it will work for me. Please check and let me know if it works.
Working Pen:
https://codepen.io/jasondecamp/pen/gryxGQ
The two changes I made were:
1) Added $parent to the reference to 'query' in the input field ng-model. I am not that familiar with ionic, but my guess is that ion-content directive adds a child scope so to reference query you need to look to the parent.
<input type="search" ng-model="$parent.query" placeholder="Search Slugname">
2) I changed the http get url to be https because I was getting insecure access warnings.
As a note, you should not need to use any JSON parsing function when the response is pure JSON data, because angular $http service will automatically recognize the data and convert it into a js object.

Why can't I retrieve data from my Json file?

I'm trying to get data from my json file for a small test project. I'm not getting any error in the developer tools and when I do console.log(data) after the request I get data from the file.
This is my angular code:
var app = angular.module('myApp', []);
app.controller('MainController', ['$scope','$http', function($scope, $http){
$scope.todos = [];
$http.get('db/todos.json')
.then(function(data){
$scope.todos = data;
});
}]);
This is my html file:
<!doctype html>
<html ng-app="myApp">
<head>
<base href="/">
<title>My todo</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://code.angularjs.org/1.5.5/angular.js"></script>
<script src="/js/app.js"></script>
</head>
<body>
<div class="container" ng-controller="MainController">
<div class="row">
<h1>Your todos</h1>
<li ng-repeat="todo in todos">
{{ todo.name }}
<li>
</div>
</div>
</body>
</html>
In my site the ng-repeat just prints out six bullet points which is wrong because I've got only two entries in my json file. Also this is what I get from my console.log(data):
Object {data: Object, status: 200, config: Object, statusText: "OK"}
config: Object
data:Object
headers:(name)
status:200
statusText:"OK"
__proto__:Object
Any ideas of what I've probably missed?
When using .then the actual response data is in response.data, so your code works if you change it like this:
.then(function(response){
$scope.todos = response.data;
});

Angular URL 'trustAsResourceUrl' not working

I'm using angular-file-upload.js and uploading an image. When the upload is successful, it returns a URL to where the image is hosted, which is hosted as a blob on Azure.
The upload is successful, and the URL is returned correctly, however when I push this URL on an "images" stack to view this image in the browser, it won't work properly. For example, the URL I get back looks like this:
"https://searlesmedia.blob.core.windows.net/event-images/4_slide-archive.jpg"
Controller.js
uploader.onSuccessItem = function (fileItem, response, status, headers) {
console.info('onSuccessItem', fileItem, response, status, headers);
$scope.uploadcomplete = "Upload Successful";
var url = $sce.trustAsResourceUrl(response);
$scope.images.push(url);
};
Html
<div class="row" data-ng-repeat="image in images">
<img ng-src="{{image}}" class="img-responsive" />
</div>
Hi it looks like you miss something please see here: http://plnkr.co/edit/1PpscI4dOMYpYRf6fbUS?p=preview
angular.module('mySceApp', ['ngSanitize'])
.controller('AppController', ['$http', '$scope', '$sce',
function($http, $scope, $sce) {
$scope.image = {};
$http.get("test_data.json").success(function(data) {
console.log(data.url);
// $scope.userComments = userComments;
$scope.image.url = $sce.trustAsResourceUrl(data.url);
});
}
]);
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example64-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.16/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.16/angular-sanitize.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="mySceApp">
<div ng-controller="AppController as myCtrl">
<div class="well">
<b>{{userComments.name}}</b>:
<img ng-src="{{image.url}}">
<br>
</div>
</div>
</body>
</html>

Categories