Encountering difficulties with showing contact images in phonegap using angularjs

In my project, I encountered an issue where I can fetch and display the contact photo using simple HTML and JavaScript. However, when I attempt to do the same using AngularJS model, I encounter an error. Below is the code snippet that I am struggling with:

Below is the list where I am attempting to display the contact:

<ul class="list">

   <li class="item item-thumbnail-left" ng-repeat="contact in contactList">
            <img ng-src="{{contact.mphoto}}"/> <!--When I directly use this path (i.e., "content://com.android.contacts/contacts/30/photo"), the image displays correctly. But when fetched from the controller, I get the error: "unable to read contacts from asset folder"-->
           <h2>{{contact.name}}</h2>
           <p >{{contact.number}}</p>

   </li>
</ul>

The following is my controller setup for setting ContactList:

ContactService.find("").then(function(contacts) {
        for (var i = 0; i < contacts.length; i++)
        {
            if (contacts[i].phoneNumbers !== null)
            {
                for (var j = 0; j < contacts[i].phoneNumbers.length; j++)
                {
 var img = contacts[i].photos  != null ? contacts[i].photos[0].value : "img/default.png";

                    $scope.contactList.push({name: contacts[i].name.formatted, number: contacts[i].phoneNumbers[j].value, mphoto: img})
                }
            }
        }

Answer №1

After a long period of challenges, I have finally found the solution,

Kindly copy and paste the lines below into your App.js file to resolve the issue. The reason why the photo is not showing is because Angularjs adds unsafe: before each URL if it is not trusted.

config(['$compileProvider', function($compileProvider) {
    $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|file|blob|content):|data:image\//);
}]);

Answer №2

While working in Angular 2 with Ionic 2, I encountered a similar issue without realizing the root cause or how to implement the recommended solution in Angular 2. To provide a comprehensive solution, here is a method to resolve it using Ionic 2:

To address this issue, you need to inject sanitizer: DomSanitizer in your controller/service.

Subsequently, you should execute the following command:

sanitizer.bypassSecurityTrustUrl(photoURL)

For clarity, here is an example implementation:

export class HomePage {
  url;

  constructor(public navCtrl: NavController, platform: Platform, sanitizer: DomSanitizer) {
    platform.ready().then(() => {
      Contacts
        .pickContact()
        .then((contact) => {
          alert(JSON.stringify(contact));
          if (contact.photos) {
            var photoURL = contact.photos[0].value;
            this.url = sanitizer.bypassSecurityTrustUrl(photoURL);
          }
        });

    })
  }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The icon on my page is not displaying, and the responsive menu is also not appearing

After tweaking the @media {} settings, I noticed that the icon displays properly when reduced, but disappears completely when fully covered with {}. Additionally, my responsive menu is not visible as expected. `@import url('https://fonts.googleap ...

Any suggestions for a quicker method to manage state changes between OnMouseDown and OnMouseUp events in React?

I am attempting to create a window that can only be dragged from the top bar, similar to a GUI window. Currently, I have set up state updates based on OnMouseDown and OnMouseUp events on the top bar. However, I am experiencing slow updates as it seems to ...

Tips for choosing a particular list item using jQuery: retrieve the attribute value of 'value' and showcase it on the webpage

I have a task that requires the following: Implement an event listener so that when you click on any list item, the value of its "value" attribute will be shown next to this line. In my HTML, I have an ordered list with 8 list items. The values range fro ...

Efficiently Organizing Data Using Coldfusion Loops in Columns and Rows

My issue lies in pulling data from a database to display on my website. I have three keys/attributes (columns) - PostedDate, DataImage, and Source that need to be shown together in one div with the posted date at the top, image in the middle, and source at ...

Creating a pair of linked dropdown menus in ReactJS that open simultaneously

Having two dropdown menus can be a bit cumbersome, especially when you have functions dedicated to opening each one individually. It would be more efficient to combine them into one function for simplicity. If anyone has a solution for this, I would greatl ...

Accessing and showcasing information from a file within an application interface through the utilization of jetpack compose

Currently, I am utilizing Jetpack Compose and Kotlin in Android Studio to develop an application. The main purpose of this app is to exhibit specific songs including their titles and authors. To accomplish this task, I decided to use a JSON file to store a ...

Deciphering the creation process behind the "WhatsApp Web" front-end page

I'm currently exploring the creation process of the front-end page for WhatsApp Web, specifically focusing on the list of contacts located on the left side (<div id="pane-side">). The contact names within this list are identified by the class "e ...

Basic PHP code converted into a JavaScript function for an onSubmit event within an HTML form

I have been trying to figure this out for hours. The goal is to submit a form only if one of the inputs matches a PHP echo. To simplify the script, it looks something like this: <head> </head> <body> <?php $A = rand(0,10); $B = r ...

Utilizing localhost in tandem with Retrofit for the testing of Kotlin Android applications

For testing my backend scripting, I am using XAMPP and trying to retrieve some JSON using Retrofit. Despite following various online tutorials, I have been unsuccessful so far. The error message I keep encountering is: java.net.ConnectException: Failed to ...

NodeJS: Issue when implementing try/catch with async/await causing SyntaxError

As a newcomer to Node Js, I am struggling to understand why the code below is throwing a syntax error with catch(). I recently updated to Node JS V14. Any assistance would be greatly appreciated. async function demoPromise() { try { let message ...

Creating a personalized notification box that is compatible with various screen sizes and web browsers on android devices with the help of

After successfully implementing a custom alert box to hide the header with JavaScript, I encountered an issue when trying to use it on different browsers and Android devices. The alert box appeared misplaced on the page and was too big for certain Android ...

What is the best way to detect the presence of the special characters "<" or ">" in a user input using JavaScript?

Looking to identify the presence of < or > in user input using JavaScript. Anyone have a suggestion for the regular expression to use? The current regex is not functioning as expected. var spclChar=/^[<>]$/; if(searchCriteria.firstNa ...

AngularJS UI-Grid not displaying JSON data

Just started learning AngularJS and everything was going smoothly until I hit a roadblock... I have been struggling to display the JSON data returned from my REST service call. While hard-coding a data array in my controller works fine, displaying the act ...

Manipulating Data in TypeScript: Creating a Mutated Copy of a List of Dictionaries

After going through multiple answers, it appears that there might be a logical error. However, I am struggling to find a solution for this issue. In TypeScript/JavaScript, I have two lists of dictionaries. One list is a copy of the other for tracking purp ...

A guide on how to retrieve POST form fields in Express

My form design is quite simple: <form id="loginformA" action="userlogin" method="post"> <div> <label for="email">Email: </label> <input type="text" id="email" name="email"></input> </div> & ...

Controller experiencing unresponsive services

I'm completely new to using AngularJS and I'm having trouble fetching local JSON data for my controller. Below is my .js file: 'use strict'; angular.module('angularPlaygroundApp').factory('campaignService', functi ...

Tips for accessing a variable through request.query

When I made a call to getContents() in my client-side code: $.getJSon("/getContents", function(room){ theRoom=$("#roomName").val();//textarea's value ... }); I am now trying to figure out how to retrieve theRoom variable in getContents(), which is ...

The express post request body fails to appear, rendering it empty

Server Side Code const express = require('express'); const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended:true })); app.post('/',(req,res)=>{ console.log(req.body) }) Client Side Code const da ...

What are the best methods for improving the efficiency of a leaflet route

My map displays a path with more than 13,000 latitude and longitude points. When testing locally, everything works well. However, once the app is on a device, it becomes extremely slow and laggy. The density of the path is due to snapping it to roads. Wha ...

Reconfigure a portion of a string using Vue's dynamic replacement feature

Currently tackling a problem. In my possession is a string that essentially consists of HTML code: let htmlTitle = "<a href="/news/sky-sport-hd-in-italia-dal-18-novembr">Sky Sport HD in italia dal 18 novembre</a> | <a href="/news/ecco-il-g ...