Angular failing to display base64 image when being added to the application

I created a program where users can upload an image, preview it, and then add it to a list by clicking a button.

The preview functionality is working fine, but when attempting to add the image to the next row in the table, nothing happens...

Question

Can someone help me figure out why the image is not displaying or adding to the list? It should add the photo if the maximum slots allowed is greater than the number of images added.

As shown below, the image should be included in the following section of the table:

https://i.sstatic.net/GZc1X.png

HTML

 <div ng-repeat="campaign in campaigns" class="campaign-container">
    <div class="container">
        <h1>{{campaign.c_name}} {{$index}}</h1><strong>This Campaign you are allowed {{campaign.max_slots}} Images</strong>
        <table class="table">
            <thead>
            <tr>
                <th>Select File</th>
                <th>Preview Image</th>
                <th>Add to list</th>
                <th>Images</th>
                <!-- <th>Remove Image</th>-->
                <th>Save Campaign</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td>
                    <!-- UPLOAD IMAGE-->
                    <div class="upload-new">
                        <input type="file"  fileread="vm.uploadme" id="fileinput-{{ $index }}" onchange="angular.element(this).scope().uploadImage(this)"/>
                    </div>
                    <!-- END-->
                </td>
                <td>
                    <!-- PREVIEW IMAGE-->
                    <div class="preview">
                        <img style="height: 100px; width: 100px" ng-src="{{campaign.preview}}" alt="preview image">
                    </div>
                    <!-- END-->
                </td>
                <td>
                    <button ng-click="addImage($index)">Add image</button>
                </td>
                <td>
                    <div ng-repeat="slot in campaign.slots" class="slot">
                        <img ng-click="addImage($index)" style="height: 100px; width: 100px" ng-src="{{slots.base_image}}" alt="show image here">
                        <img ng-src="{{slots.base_image}}" />
                        <button ng-click="removeImage(slots)">Remove Image</button>
                    </div>
                </td>
                <!-- <td>Remove button to be here</td>-->
                <td>
                    <button ng-click="SaveImage()">Save to API</button>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</div>

JavaScript

     .controller('Dashboard', function ($scope, $http, $timeout) {

        $scope.campaigns = [];
        $scope.preview = '';
        // $scope.slots = [];
        // $scope.maxSlots = maxSlots;

        $scope.uploadImage = function (element, index) {
            console.log(element);
            console.log(element.id);
            str = element.id;
            str = str.substr(str.indexOf('-') + 1);
            console.log(str);
            index = str;

            // console.log('we are here');
            input = element;
            file = input.files[0];
            size = file.size;
            if (size < 650000) {
                var fr = new FileReader;
                fr.onload = function (e) {
                    var img = new Image;

                    img.onload = function () {
                        var width = img.width;
                        var height = img.height;
                        if (width == 1920 && height == 1080) {
console.log('we are here');
                            $scope.campaigns[index].preview = e.target.result;
                            // $scope.preview = e.target.result;
                            $scope.perfect = "you added a image";
                            $scope.$apply();

                        } else {
                            $scope.notPerfect = "incorrect definitions";
                        }
                    };
                    img.src = fr.result;
                };

                fr.readAsDataURL(file);
            } else {
                $scope.notPerfect = "to big";
            }
        };

        $scope.addImage = function (campaign) {
            if(!campaign) return;
            if ($scope.length < campaign.max_slots) {
                $scope.slots.push({
                    "slot_id": $scope.length + 1,
                    "base_image": $scope.preview,
                    "path_image": ""
                });
            } else {
                window.alert("you have to delete a slot to generate a new one");
            }
        };

Answer №1

Your view and model are not consistent due to naming issues. I recommend updating your addImage function as follows:

$scope.addImage = function (campaign) {
    if(!campaign) return;
    if (campaign.slots.length < campaign.max_slots) {
        campaign.slots.push({
            "slot_id": $scope.length + 1,
            "base_image": campaign.preview,
            "path_image": ""
        });
    } else {
        window.alert("Please delete a slot before adding a new one");
    }
};

Make sure your binding is set up like this:

<div ng-repeat="slot in campaign.slots" class="slot">
    <img style="height: 100px; width: 100px" ng-src="{{slot.base_image}}" alt="show image here">
    <img ng-src="{{slot.base_image}}" />
    <button ng-click="removeImage(slot)">Remove Image</button>
</div>

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

Grab every piece of JavaScript code and styling from the HTML document and transfer it into a textarea field

Below is my code that extracts the JavaScript like this: src="assets/js/jquery.min.js" src="assets/smooth-scroll/smooth-scroll.js" I want it to look like this: (I believe my regex is incorrect): <script src="assets/js/jquery.min.js"></script> ...

Exploring the world of unit testing with Jest in Strapi version 4

In my quest to conduct unit tests using Jest for the recently released version 4 of Strapi, I have encountered some challenges. The previous guide for unit testing no longer functions as expected following the latest documentation updates. Despite my effor ...

Unable to function properly on Backbone.js, events have been rendered ineffective

I have recently created a view with the following code snippets: var app = app || {}; app.singleFlowerView = Backbone.View.extend({ tagName: 'article', className: 'flowerListItem', // specifies where to render the views templ ...

Tips on utilizing an array of json key names for fetching data from a json object

Is there a way in React to reuse a table by passing the interest (the data you want to display) and JSON data? When iterating over both the interest array and the data, it works correctly. However, when trying to use different APIs with different data st ...

The functionality of the Eslint object-property-newline feature is not functioning as expected

Within my configuration file .eslintrc, I have set "object-property-newline": ["error", { "allowAllPropertiesOnSameLine": true }], and "max-len": "off". However, objects like const something = {a: 5, ffsdfasdasdsddddd: 'asdasdasdddddddddddssssssddddd ...

jQuery does not have the capability to automatically calculate Value Added Tax on form submissions

I have included this section in my form to calculate the value added tax (VAT): <div class="col-md-4"> <div class="form-check"> <input type="radio" id="vat_on" name="vat" value=&q ...

Display the matrix in a semi-spiral pattern

I am working with a 3 by 5 matrix, filled with numbers from 1, presented as follows: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 The task is to print the values in a half-spiral order, starting from the bottom left vertically: 11 6 1 5 10 15 12 7 2 4 9 ...

Is it possible to resize my image according to the screen size using html/css, or is resizing not the problem at all?

I've encountered this issue several times, but I'm unable to pinpoint the problem. The page looks fine at a specific size, but when I start testing and scaling down to around 1260px width, the image overflows creating white space. Removing one of ...

Rails backend is struggling to receive Crossrider ajax post requests with JSON payload

I am encountering an issue where my attempts to post a JSON object to a remote server (Rails) are failing. The POST parameters seem to be converted to a url-encoded string instead of being sent as 'application/json'. Here is an example of what I ...

"Capturing" AJAX requests from Capybara / Selenium - Rails

Is it possible to monitor real AJAX requests in feature specs using Capybara/Selenium while my app is making AJAX calls on specific events like .click? I attempted to utilize the Teaspoon gem, but it seems to only allow access to fixture URLs (as mentione ...

Execute npm build in sbt for play framework

Exploring sbt/play configuration is a new challenge for me. Working with play 2.3.8 to host my javascript application, my project utilizes: .enablePlugins(SbtWeb) .enablePlugins(play.PlayScala) .settings( ... libraryDependencies ++= WebDependancies :+ ...

The Photoswipe default user interface cannot be located

While attempting to incorporate PhotoSwipe into my website, I encountered an uncaught reference error related to The PhotoswipeUI_Default is not defined at the openPhotoSwipe function Below is the code snippet that I have been working on: <!doctyp ...

Dynamic Button with Jquery and CSS Grid

I have a div that includes a heading using and a Vertical Navigation menu in the same container. To ensure responsiveness, I utilized media queries along with "Display:none and position:abolute" for the Navigation Container, which worked flawlessly up to ...

Challenges with the Placement of Buttons

I am facing an issue with the code below: document.addEventListener("DOMContentLoaded", function(event) { // Select all the read more buttons and hidden contents const readMoreButtons = document.querySelectorAll(".read-more"); const hiddenConten ...

Access the extended controller and call the core controller function without directly interacting with the core controller

i have a core controller that contains an array called vm.validationTypes with only 2 objects. I need to add 3 or 4 more objects to this array. to achieve this, i created another controller by extending the core controller: // CustomValidation angular.m ...

The title of the Electron application remains consistent

My application is being packaged using electron-packager, but it's not changing its name and still displays "Electron." It's supposed to use the productName in my package.json file, but for some reason, it doesn't change. Even after creati ...

Is there a way to transfer innerHTML to an onClick function in Typescript?

My goal is to pass the content of the Square element as innerHTML to the onClick function. I've attempted passing just i, but it always ends up being 100. Is there a way to only pass i when it matches the value going into the Square, or can the innerH ...

Unleashing the power of TypeScript with Solid JS Abstract Class

Why am I getting an undefined error for my calcUtilisation method when using an Abstract Class as the type in createStore? Is there a way to utilize a type for the data along with a method within the same class for createStore? abstract class Account { ...

Having trouble applying styles to a component using forwardRef

I'm relatively new to React and still trying to wrap my head around the component's lifecycle. However, the issue at hand is proving to be quite perplexing. One thing that confuses me is why adding "setState(10);" causes the style of the "Test" ...

What could be causing one of my images to not appear on my Gatsby page?

Hey there, I could use some help with this issue: Recently, I created a website using Gatsby.js and deployed it to my web server (which is running NGINX on Ubuntu 20.04). The site uses Gatsby Image for querying and displaying images, and everything seems t ...