Hien Luong
Hien Luong

Reputation: 520

fetch and load image in angularjs

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

Upvotes: 0

Views: 13352

Answers (2)

J-Dizzle
J-Dizzle

Reputation: 3191

Basically, yes. Check the docs for ng-src

<img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />

Upvotes: 3

dting
dting

Reputation: 39287

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="https://i.sstatic.net/{{funcName(post.id)}}" />
  </div>
</div>

1 2

Upvotes: 3

Related Questions