I'm fetching post data from facebook on my website, but the json data does not contain full size image. So I have to fetch image from other source.
post data example:
{
"data": [{
"id": "1",
"from": {
"category": "Company",
"name": "Example",
"id": "12"
},
{
"id": "2",
"from": {
"category": "Company",
"name": "Example1",
"id": "112"
}
]}
so, the facebook post should have images and it fetches from different source. Each time I want to get image of a post, I will fetch data based on post id
{
full_picture: 'http://linkhere'
}
my page is using angularjs to display post content.
<div ng-repeat="post in postsList">
<div>{{post.id}}</div>
<img src="???" />
</div>
Basically, I will use post id to get image url, but I dont know how to call the function to get image url based on the post id. Do we have the way in angularjs that passing something like
<image ng-src="funcName({{post.id}})" />
I'm totally new with angularjs framework, so I appreciate all ideas
You don't need the expression to call your function with post.id. You do however, need the function inside an expression for ng-src.
<image ng-src="{{funcName(post.id)}}" />
var app = angular.module('app', []);
app.controller('myController', function($scope) {
$scope.posts = [{id: 1}, {id: 2}];
$scope.funcName = function(id) {
return IMAGES[id];
};
});
var IMAGES = {
1: 'BoCw8.png',
2: 'Ed3JT.png'
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app='app' ng-controller='myController'>
<div ng-repeat="post in posts">
<image ng-src="http://i.stack.imgur.com/{{funcName(post.id)}}" />
</div>
</div>
Basically, yes. Check the docs for ng-src
<img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
Related
I am developing a simple hybrid mobile app using the Ionic framework. When you search for a last name, a GET request is sent to retrieve all matching last names, and then displays their corresponding ID's. I am having an issue displaying the returned data from the JSON object.
Below is the html page:
<ion-view view-title="Account" ng-controller="AccountCtrl">
<ion-content>
<div class="list">
<div class="item item-input-inset">
<label class="item-input-wrapper">
<input type="text" placeholder="Search" ng-model="name">
</label>
<button class="button button-small" ng-click="searchUser(name)">
Go
</button>
</div>
</div>
<div>
<ul ng-repeat="user in $results">
<li>{{user.id}}</li>
</ul>
</div>
</ion-content>
Next is the js file that successfully returns a populated JSON object with everything I need.
angular.module('starter.controllers', [])
.controller('AccountCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.searchUser = function (name) {
$http.get('https://notrelevantforthis/searchLastName?=' + name).then(function (response) {
console.log(response.data)
//Assign JSON obj to results to repeat through and display data
$scope.results = response.data;
//To show the actual JSON object is returned
//var jsonStr = JSON.stringify($scope.results);
//document.body.innerHTML = jsonStr;
}, function (error) {
console.log(error)
});
};
}]);
Now the important part is the structure of the JSON object itself. I think this is where I am getting confused. The structure is like the following:
{
"response": {
"totalFound": 275,
"start": 0,
"acc": [
{
"id": [
"1"
],
"first_name": [
"Joe"
],
"last_name": [
"Smith"
]
},
{
"id": [
"2"
],
"first_name": [
"John"
],
"last_name": [
"Doe"
]
}]}
}
My problem is iterating through the JSON object using ng-repeat I think. For some reason none of the data is being displayed, but the object is definitely there when looking at the console. Any help or direction in what I am doing wrong would be much appreciated, as I am new to this and have been trying to find the correct way to do this.
EDIT:
Tried using collection-repeat as well offered by the ionic framework but was getting stack limit errors.
When you're assigning response.data to $scope.results, you're literally assigning the HTTP's response body to it, which is the whole JSON object that you have in your question. You would need to actually point to response.data.response.acc if you wanted to ng-repeat through those accounts.
In your template, it should just be ng-repeat="user in results", without the $ in front of results.
Your JSON object lists the id for each account as an array, I'd recommend just giving the literal value without the array, otherwise in your ng-repeat you'll have to use {{user.id[0]}} to actual print the value without printing the array itself.
I've created an example for you here: http://plnkr.co/edit/GYeF4FzVHl8Og5QTFcDx?p=preview
I am using angular with bootstrap modal,i have a json stored in a scope variable products in a controller as follow
controllers.productController = function($scope) {
$scope.products = {"meta": {"total_count": 3}, "objects": [{ "id": 3, "image": "/media/products/1/Product007_image.JPEG", "image2": "/media/products/1/Product007_image2.JPEG",}, {"id": 4, "image": "/media/products/1/Product009_image.JPEG", "image2": "/media/products/1/Product009_image2.JPEG"},{"id": 13, "image": null, "image2": null}]}
$scope.fetchModal = function(index) {
$scope.activeProd = index;
$('#product_desc').modal();
}
}
index.html
<div ng-controller="productController">
<div class="product-list">
<span ng-repeat="product in products.objects" ng-click="fetchModal(index)" >{{ product.id }}</span>
</div>
<div id="product_desc">
<img ng-src="{{products.objects[activeProd].image }}" />
{{ products.objects[activeProd].id }}
</div>
</div>
it works all fine, the problem is that if i click on a product in product-list which has image it renders modal with image and then click on a product which have image value null i.e no image, in its model the previous product image still exist instead i should get nothing. I hope i am clear to my point
i observed that the ng-src is changing and assigning to null but the src attribute is not changing
I think your problem is that when you change the ng-src to null the older value is retained in the image source.
This is the proper angular behavior. You can find the details on this thread :
https://stackoverflow.com/a/22094392/1649235
If you go through this thread you will also find a workaround i.e. don't put your image path as null where it is supposed to be empty, put it equal to '//:0'.
I have a somewhat deep JSON object I am trying to using in an HTML template.
{
"service": {
"name": "example",
"url": "abc.com",
"template": "/abc/def/v1",
"metadata": {
"password": "dontguessme",
"username": "supereasy"
}
}
}
I am including a template with the following HTML code.
<div class="modal-body" ng-include="service.instructionsTemplate"> </div>
In the template there is the following.
<h1>Some example content</h1>
{{service.metadata.password}}
My question is instead of referencing the field password via service.metadata, is there a way I can reference it with just the variable password.
I was trying to dig through some of the Angular docs around scoping and templates but came up empty. I saw you can use ng-init.
I was able to use ng-init="metadata = service.metadata" and was able to reference the field password in the template via metadata.password.
However I would just like to reference it by password.
Any ideas?
You already did ng-init="metadata = service.metadata", why not going a step further and do ng-init="password = service.metadata.password"?
Another way would be to bind $scope.password = service.metadata.password inside the controller thayou're using on that page
Edit: OP asked a more general solution
If you don't know the property names, then your best move would be to bind the metadata object, like you already did, and then iterate through its properties using ng-repeat
in your controller:
$scope.metadata = service.metadata
in your template (view):
<h1>Some example content</h1>
<ul>
<li ng-repeat="element in metadata">{{element}}</li>
</ul>
You can easily set the password to something inside the controller:
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.data = {
"service": {
"name": "example",
"url": "abc.com",
"template": "/abc/def/v1",
"metadata": {
"password": "dontguessme",
"username": "supereasy"
}
}
};
$scope.password = $scope.data.service.metadata.password;
});
Here is a demo: http://plnkr.co/edit/KrKeLIP2ANd0rl5NLywF?p=preview
Im trying to load some data from a local json file and put it inside a jquery mobile listview using angularJS. Im having a hard time to understand how do I combine the ng-repeat with the data-role="listview".
For the fiddle example i used an online hosted json file from filltext.com.
i updated the code according to Danyu's suggestion, but it still doesnt work. Now all the usernames appear in ONE li element, instead of one username in one li element.
fiddle link:
http://jsfiddle.net/hh8hS/
html code:
<div data-role="page" id="scientists" ng-app="test">
<div data-role="header"><h3>jquery mobile + json call test</h3></div>
<div data-role="content">
<div ng-controller="controller">
<ul data-role="listview" data-inset="true" data-filter="true">
<li ng-repeat="item in itemSet">{{item.username}}</li>
</ul>
</div>
</div>
</div>
JS code:
var data1= [
{
"id": 1,
"email": "RWahl#vitae.net",
"username": "NCollier",
"password": "XIsyw"
},
{
"id": 2,
"email": "AKahlig#eget.net",
"username": "NDerucher",
"password": "f687l"
},
{
"id": 3,
"email": "KKirkley#sagittis.com",
"username": "DBario",
"password": "Vl7ND"
},
{
"id": 4,
"email": "NMcgarity#magna.com",
"username": "LOng",
"password": "JeTnK"
}
];
var myApp=angular.module("test",[]);
myApp.controller("controller", function($scope,$http){
$http.get("data1").success(function(data){
$scope.itemSet=data;
});
});
EDIT:
apparently the code works with the little change Danyu suggested, it was a local problem on my PC.
You should use ng-repeat on the <li> element instead of the parent <ul>:
<li ng-repeat="item in scientists">
{{item.username}}
</li>
Here is the basic setup, which has a default noemployee.html partial: as the ng-view
Index.html content:
<div id="container" ng-controller="EmployeeCtrl">
<!-- Side Menu -->
<span id="smenuSpan">
<ul id="thumbList">
<li ng-repeat="employee in employees | filter:categories">
<img class="smallImage" ng-src="content/app/images/{{employee.image}}" alt="{{employee.description}}">
</li>
</ul>
</span>
<!-- Content -->
<span id="contentSpan">
<div ng-view></div>
</span>
</div>
My Route Provider:
var EmployeeModule = angular.module('EmployeeModule', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/', { templateUrl: 'content/app/partials/noemployee.html', controller: EmployeeModule.EmployeeCtrl });
$routeProvider.when('Employee/:id', { templateUrl: 'content/app/partials/employee.html', controller: EmployeeModule.EmployeeCtrl });
$routeProvider.otherwise({ redirectTo: '/' });
$locationProvider.html5Mode(true);
My Controller:
function EmployeeCtrl($scope, $http, $routeParams, $timeout) {
$scope.employees = [
{ "id": 1, "category": "ones", "image": "person1.jpg", "description": "person 1 description", name:"Jane Smith" },
{ "id": 2, "category": "twos", "image": "person2.jpg", "description": "person 2 description", name: "Mark Sharp" },
{ "id": 3, "category": "threes", "image": "person3.jpg", "description": "person 3 description", name: "Kenny Suave" },
{ "id": 4, "category": "fours", "image": "person4.jpg", "description": "person 4 description", name: "Betty Charmer" },
{ "id": 5, "category": "fives", "image": "person5.jpg", "description": "person 5 description", name: "John Boss" }
];
$scope.employeesCategories = [];
$scope.currentEmployee = {};
$scope.params = $routeParams;
$scope.handleEmployeesLoaded = function (data, status) {
//$scope.images = data;
// Set the current image to the first image in images
$scope.currentEmployee = _.first($scope.employees);
// Create a unique array based on the category property in the images objects
$scope.employeeCategories = _.uniq(_.pluck($scope.employees, 'category'));
}
$scope.fetch = function () {
$http.get($scope.url).success($scope.handleEmployeesLoaded);
};
$scope.setCurrentEmployee = function (employee) {
$scope.currentEmployee = employee;
};
// Defer fetch for 1 second to give everything an opportunity layout
$timeout($scope.fetch, 1000);
}
Observations:
At present, if I click on any employee, no 'Employee/??' is added to the address bar path [ which isn't a crime to me], however, the main content div does not change the partial to the employee.html.
If I comment out "$locationProvider.html5Mode(true);", the default localhost is now "http://localhost:31219/#/" and when I click on any employee the address bar shows 'http://localhost:31219/Employee/1', and the page is navigated away to a 404 error page.
I know I am bastardizing something here that the solution is so simple it escapes me.
Goals:
I really would like to avoid hash tags in my address bar.
It would be nice but no req that the employee/id not show up in the address bar but I suspect the partial cannot change w/o it. and, naturally
I want the partial to change to the 'employee.html" page when an employee is clicked.
Does anyone see where I am going wrong with this code?
Thanks in Advance!
Solution:
I needed to put '#/' in the img href --> href="#/Employee/{{employee.id}}"
Comment out
'$locationProvider.html5Mode(true);'
As a side note, I sure wish I knew how to get this to work w/o those pesky hash tags. Any ideas anyone?
In order to use html5mode, your server has to serve up the main app index file for otherwise invalid routes.
So, for example, if your server side code handles CRUD operations on paths like: /api/employees, /api/employees/:id, etc...
and it serves up static content, images, html, css, js, etc.
For any other request, that would otherwise be a 404, it should, instead of responding with a 404, respond with a 200 code, and serve up the index.html file.
This way any non static and non server side route gets handled by the angular app.
This is mentioned in the Angular guide on this page: http://docs.angularjs.org/guide/dev_guide.services.$location
Note the 'server side' comment at the end:
Html link rewriting
When you use HTML5 history API mode, you will need
different links in different browsers, but all you have to do is
specify regular URL links, such as: link
When a user clicks on this link:
In a legacy browser, the URL changes to /index.html#!/some?foo=bar
In a modern browser, the URL changes to /some?foo=bar In cases like the
following, links are not rewritten; instead, the browser will perform
a full page reload to the original link.
Links that contain target element
Example: link
Absolute links that go to a different domain
Example: link
Links starting with '/' that lead to a different base path when base is defined
Example: link
Server side
Using this mode requires URL rewriting on server side, basically you have to rewrite
all your links to entry point of your application (e.g. index.html)
This was the problem:
<img class="smallImage" ng-src="content/app/images/{{employee.image}}" alt="{{employee.description}}">
Solution:
I needed to put '#/' in the img href --> href="#/Employee/{{employee.id}}"
Comment out '$locationProvider.html5Mode(true);'
As a side note, I sure wish I knew how to get this to work w/o those pesky hash tags. Any ideas anyone?