Using Angular's ng-repeat to iterate through an array and display its objects within another array

One of my tasks involves retrieving json objects through a simple post method.

The json contains multiple campaigns, organized in an array structure.

Each campaign holds slots, which are also arrays with one or more base_image elements.

My goal is to display information for each individual campaign on the screen.

  • max_slots
  • c_name
  • slots.base_image

This way, I can showcase the name of each campaign, the maximum number of allowed slots, and the associated images within each campaign.

PURPOSE

I am currently working on implementing an image upload and preview feature for each campaign. The objective is to only show the uploaded image preview within the specific campaign it belongs to.

ISSUE

However, upon uploading an image, the preview is displayed across all campaigns instead of being linked to the individual campaign.

Refer to the image below:

https://i.stack.imgur.com/dKF46.png

HTML

<body ng-app="myApp">
<div ng-controller="Dashboard">
    <!--FIRST ng-repeat-->
    <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 id="fileinput" ng-model="file" type="file" ng-model-instant="" name="file"
                                   accept="image/*"
                                   onchange="angular.element(this).scope().uploadImage(this)">
                        </div>
                        <!--END-->
                    </td>
                    <td>  <!--PREVIEW IMAGE-->
                        <div class="preview">
                            <img style="height: 100px; width: 100px" ng-src="{{preview}}" alt="preview image">
                        </div>
                        <!--END--></td>
                    <td>
                        <button ng-click="addImage()">Add image</button>
                    </td>
                    <td>
                        <div ng-repeat="slot in campaign.slots" class="slot">
                            <img ng-click="addImage()" style="height: 100px; width: 100px" ng-src="{{base_image}}"
                                 alt="slot image">

                            <button ng-click="removeImage(slot)">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>
    <!--END FIRST ng-repeat-->
</div>
</body>

JavaScript

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

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

        $scope.uploadImage = function () {
            // console.log('we are here');
            input = document.getElementById('fileinput');
            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) {
                            $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 (index) {

            if ($scope.campaigns[index].slots.length < $scope.campaigns.maxSlots) {
                $scope.campaigns[index].slots.push({
                    "slot_id": $scope.campaigns[index].slots.length + 1,
                    "base_image": $scope.preview,
                    "path_image": ""
                });

            } else {
                window.alert("you have to delete a slot to generate a new one");
            }
        };

$scope.GetData = function () {
            $http({
                url: "http://www.site.co.uk/ccuploader/campaigns/getCampaign",
                method: "POST",
                date: {},
                headers: {'Content-Type': 'application/json'}
            }).then(function (response) {
                // success
                console.log('you have received the data ');
                // console.log(response);
                $scope.campaigns = response.data;
                console.log("logging campaings", $scope.campaigns);
                //$scope.slots = response.data[0].slots;
                //$scope.maxSlots = response.data[0].maxSlots;

            }, function (response) {
                // failed
                console.log('failed getting campaigns goo back to log in page.');
                // console.log(response);
            });
        };

        $scope.GetData();
    })

Answer №1

Ensure that each campaign has its own preview variable in the controller. Consider passing the index of the campaign to the uploadImage function.

It seems like the method for handling file inputs may need adjustment. Here is a suggested template and controller setup:

Template:

<input type="file" onchange="angular.element(this).scope().uploadImage(this, $index)">

<img ng-src="{{campaign.preview}}" alt="preview image">

Controller:

$scope.uploadImage = function (element, index) {
    // Avoid using getElementById with ng-repeat, instead utilize element or index arguments
    // input = document.getElementById('fileinput');
    // ...

    if (width == 1920 && height == 1080) {
         $scope.campaigns[index].preview = e.target.result;
    }
}

The mentioned issue of using getElementById for multiple elements can be resolved by generating unique IDs based on the index:

<input id="fileinput-{{ $index }}" 

Edit: The original poster implemented the above solution with some modifications:

HTML

<input id="fileinput-{{ $index }}" ng-model="file" type="file" ng-model-instant="" name="file" accept="image/*" onchange="angular.element(this).scope().uploadImage(this)">

Controller

    $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";
            }
        };

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

Struggling to implement SOAP web service in AngularJS

I'm working on consuming a webservice using the Get method in AngularJS. In my controller, I've used $http to write the code. However, I'm not receiving any response and I'm unsure if the URL is being hit or not. Any corrections or su ...

Utilizing window.matchMedia in Javascript to retain user selections during page transitions

I am encountering difficulties with the prefers-color-scheme feature and the logic I am attempting to implement. Specifically, I have a toggle on my website that allows users to override their preferred color scheme (black or light mode). However, I am fac ...

ajax-jquery request declined

I have a jquery-ajax function that is being called multiple times with different IP addresses each time. This function makes a call to an action in the mvc4 controller responsible for executing a ping and returning the results. After analyzing the request ...

What is the best way to navigate from a button in NextJS to another page that I have built within the same application?

As I work on developing a website for a pet rescue charity using Next.js, I am facing an issue with getting my button or link to function correctly. Every time I try to navigate to another page within my Next.js app, I encounter a 404 error stating "This p ...

Encountering a bug in my JSON or object tree viewer in Vue.js 3 where duplicate keys are present when there are multiple similar values

Encountering an issue with the following code: Attempting to create a tree viewer from an object, it works well until encountering identical values which cause key duplication and replacement. View on CodePen: https://codepen.io/onigetoc/pen/rNPeQag?edito ...

JavaScript - Need to automatically scroll to a different div when scrolling occurs

Currently, my focus is on creating a single-page website where the main content is displayed in large boxes arranged vertically down the page. If you have any suggestions or thoughts on using JavaScript to navigate to each content box more efficiently, I ...

Adding middleware to the res.render() function can be extremely helpful when dealing with a large number

Recently, I put together a webpage for local use and it involves many routes. Specifically, I have 31 .ejs files and 3 .html files all neatly stored in the "views" folder. //app.js - using node and express app.get('/page1', function(req, res ...

Express JS causing NodeJS error | "Issue with setting headers: Unable to set headers after they have been sent to the client"

As I embark on my journey to learn the fundamentals of API development, I am following a tutorial on YouTube by Ania Kubow. The tutorial utilizes three JavaScript libraries: ExpressJS, Cheerio, and Axios. While I have been able to grasp the concepts being ...

Encountered an issue while attempting to assess Jackson deserialization for this specific

I am currently in the process of establishing a many-to-many relationship between movies and users. However, I encountered an error while attempting to save a movie: 2017-12-01 16:12:43.351 WARN 17328 --- [nio-8090-exec-5] .c.j.MappingJackson2HttpMessageC ...

Tips for modifying the href attribute when a user clicks

Is there a way to dynamically change the value of this link <a href="/Countries/388/10">next</a> without having to refresh the page? For example, if a user clicks on the link, it should update to <a href="/Countries/388/20">next</a&g ...

What could be causing the malfunction in this JavaScript and WebRTC code?

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Vid Chat App</title> </head> <body> <video controls autoplay> </video> <script src="https: ...

Ways to emphasize search outcomes in Flask/HTML?

I am currently working on creating a search box using HTML and the Flask framework in Python. Below is the layout I am working with: Layout My goal is to input text into the search box and have it highlighted within the text area on the same HTML page. F ...

Using jQuery and AJAX to dynamically add data to POST parameters

Hello, I have a question that may sound like one from a newbie. I am trying to figure out how to insert a variable into a parameter for a POST request instead of simply writing the number in directly: var x = 3; id=(the var x needs to be here)&appid=4 ...

Creating an application for inputting data by utilizing angular material and javascript

I am looking to create an application using Angular Material Design, AngularJS (in HTML), and JavaScript. The application should take input such as name, place, phone number, and email, and once submitted, it should be stored in a table below. You can fin ...

Conflicting Angular components: Sorting tables and dragging/dropping table rows

In the current project I'm working on, I've integrated both angular table-sort and angular drag-drop. However, I ran into an issue where dragging a row and attempting to drop it onto another row causes the table sort to forcefully rearrange the r ...

When using jquery.hide() and show(), the content within the div disappears momentarily before reappearing

Hello! I am experiencing an issue where the content of my div disappears after using a jQuery hide() and show() function. It seems to be gone. <li class="gg3"><a class="link" href="#" data-rel="content3">Link1</a></li> <div clas ...

Exploring the world of routing parameters in Express.js and AngularJS

Struggling to configure routes with parameters in an AngularJS application supported by a node.js server running on express. The setup involves Node routing all unspecified paths to a catch-all function: app.use(express.bodyParser()); app.use(app.router); ...

What is the most efficient way to transfer a large search results array between NodeJS and AngularJS?

My application is built with NodeJS for the back-end and AngularJS for the front-end. I've run into an issue where sending a search query from Angular's $http to the back-end results in a bottleneck when there is a slow internet connection. Angul ...

Enhance the progression bar using JavaScript

Is there a way to dynamically update a progress bar in HTML while a function is running? function fillProgressBar() { var totalIterations = 100; for (var i = 1; i <= totalIterations; i++) { //perform calculations progressBarWidth = (i/to ...

Encountered an issue with mapping data from a controller to a view in Angular.js

Currently, my application consists of only three small parts: a service that makes an http call to a .json file, a controller that receives data from the service and sends it to a view. Everything was working fine when I hard coded the data in my service. ...