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

Tips for deactivating all JavaScript events on a webpage that has been loaded within an iframe

My website is equipped with various JS click/mouseover/mouseout/scroll events and incorporates several JS libraries to operate features such as carousels, bootstrap modal pop-ups, and more. I am looking to halt all events on a specific element. Although I ...

Is the textarea's shape out of the ordinary?

Most textareas are typically rectangular or square in shape, similar to this: However, I am interested in having a custom-shaped textarea, like the example below: Is it feasible to achieve? ...

Ways to showcase information from an angular service

I'm struggling with displaying data from a service in my HTML view using AngularJS. My goal is to show a list of submitted forms called Occurrences in the view. When clicking on a list item, I want to be able to view all the data fields submitted thro ...

Creating a password with two distinct numbers using regular expressions

In javascript I am struggling to create a password that meets the criteria of having at least eight characters, including two SEPARATE digits, one uppercase and one lowercase letter, as well as one special character (-, @, #, $, &, *, +) but not /, !, ? ...

Default Value for Null in Angular DataTable DTColumnBuilder

What is the best way to define a default value in case of null? $scope.dtOptions = DTOptionsBuilder .fromSource('api/Restt/List'); $scope.dtColumns = [ DTColumnBuilder.newColumn('modi ...

Troubleshooting compatibility issues between jQuery scrollLeft and Angular

As I attempt to programmatically scroll a horizontally overflowing div, I am confident that my final code should resemble the following: var $element = $('#widgetRow');//or maybe $('#widgetRow').parent(); //With 1 or more parent()& ...

converting a JSON array into an object

I seem to be facing a challenge: I have a JSON list with rows of data and a JSON object. My goal is to iterate through the list and assign the rows to different objects within the JSON structure. The first and last elements in the list are empty, followe ...

What method is most effective for duplicating objects in Angular 2?

Is it just me, or does Angular 1.x have methods on the global angular object like angular.copy and angular.shallowCopy that are missing in Angular 2? It seems like there is no equivalent version in Angular 2 documentation. If Angular 2 doesn't plan on ...

The second jQueryUI datepicker instance flickers and vanishes when the show() function is triggered

I currently have two jQueryUI datepickers integrated into my webpage. The initialization code for both is as follows: jQuery("#departureDate").datepicker({ beforeShow: function() { getDatesForCalendar("outbound"); }, numberOfMonths: 3 ...

What is the method for retrieving data from the root component within a child template in VueJs?

How can I access this.$root from within a VueJs template? For example: <template> <v-card elevation="this.$root.$refs.foo.cardElevation"> Foo </v-card> </template> I am aware that I can create a data property and ...

Component fails to update when attribute is modified

My issue is that the crud-table component does not refresh when I change currentTable. It works when I assign currentTable = 'doctor' in the created() hook, but not here. Why is that? <template> <div id="adminpanel"> <div id ...

The JavaScript .load() function fails to run

Attempting to create a straightforward Newsfeed page based on user interests. Here is the code I have implemented for this purpose. The issue I'm facing is that while the code works fine on my local server, it encounters problems when running on an on ...

Passport.js does not provide authentication for server-side asynchronous requests

Recently, I configured Passport.js with the local-strategy on my express server. Interestingly, when I am logged in and send an asynchronous request within NextJS's getInitialProps, it allows the GET request through client-side rendering but not serv ...

Secure User Verification in Laravel 5 and AngularJs sans the need for JWT Tokens

I am currently working on a project that involves utilizing a Laravel-based back-end and a front-end built with both Laravel and AngularJS. After completing 40% of the back-end development, I am now faced with the task of implementing the front-end. Howev ...

Utilizing Axios for Vue Multiselect on select/enter Event

I have successfully implemented a Vue Multiselect feature that retrieves options from my database using an axios call. This functionality works great as it allows users to select existing options or add new ones to create tags. While this setup is working ...

Sending an array of objects within another array to an Android device - here's how

Having trouble with this code showing Invalid JSON. Any suggestions for an Android-friendly alternative? Proposed Format:--> { "supplyType":"O", "subSupplyType":"1", "subSupplyDesc":"TESTDESCRIPTION", "docType": "BIL", ...

Looking for a way to extract Regular Expressions from an IgGrid cell in Infragistics?

Is it possible to apply a regular expression to a igTextEditor within an igGrid Updating? I attempted to utilize the validate option, but it was unsuccessful. $("#schedulerTable").igGrid({ columns: $scope.schedulerColumns, widt ...

The distinction between a JSON file that is generated dynamically from a response and one that is

I've been working on configuring a bootstrap typeahead feature and here is the jquery code I am using: $(function () { $.ajax({ type: "GET", url: "http://example.com/search?callback=my_callback", data: { keyword: &apos ...

Any number of elements in a single JSX code snippet

In my React code, I've created a function called optionTemplate to be used as a prop in a React component. const optionTemplate = (option) => { return ( <div className="flex align-items-center gap-2" style={ ...

Using Node.js to retrieve table data from a URL

My journey with Node JS and express is just beginning as I dive into building a website that serves static files. Through my research, I discovered the potential of using NodeJS with Express for this purpose. While I have successfully served some static HT ...