Can values be transferred from an ng-repeat to a JavaScript function?

I am facing an issue with this segment:

<tr ng-repeat="data in filtered = (list | filter:search | orderBy : predicate :reverse) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit">
                    <td>{{data.name}}</td>
                    <td>{{data.price}}</td>
                    <td>{{data.img}}</td>

<script type="text/ng-template" id="myModalContent.html">
                    <div class="modal-header">
                        <h3 dir="rtl" align="center">screenshot</h3>
                    </div>
                    <form ng-submit="submit()">
                      <div class="modal-body">
                        <img ng-src="{{data.img}}">
                      </div>
                      <div class="modal-footer">
                          <button class="btn btn-warning" ng-click="cancel()">close</button>
                      </div>
                    </form>
                </script>
                    <button ng-click="open()">open</button>

When attempting to pass the value from {{data.img}} to the JavaScript function that triggers a modal window, it is not working correctly. Do you have any solutions or suggestions?

Thank you!

Answer №1

In order to properly address this issue, it is essential to pass the column reference into the modal. Otherwise, we will not be able to determine which image should be displayed.

$scope.open = function (imageKey) {
    $modal.open({
        templateUrl: 'myModalContent.html',
        backdrop: true,
        windowClass: 'full',
        controller: function ($scope, $modalInstance, data, imageKey) {
            $scope.data='';
            $scope.data = data;

            $scope.getImage = function () {
                return $scope.data[imageKey];
            }

            $scope.cancel = function () {
                $modalInstance.dismiss('Close');
            };
        },
        resolve: {
            data: function() {
                // access outer controller scope by using $scope.$parent
                return $scope.$parent.data;
            },
            imageKey: function() {
                return imageKey;
            }
        }
    });
}

In the template (provide the key you wish to use):

<button ng-click="open('dioPlusImage')">Open Screenshot</button>

In the modal template:

<img ng-src="{{getImage()}}>"

Answer №2

It seems like you have included the bootstrap-modal tag, indicating that you are using a modal.

To pass a variable into the modal, you can utilize the resolve key when opening the modal. Make sure the modal demo includes this step.

var modalInstance = $modal.open({
  animation: $scope.animationsEnabled,
  templateUrl: 'myModalContent.html',
  controller: 'ModalInstanceCtrl',
  size: size,
  resolve: { // include your variable here
    items: function () {
      return $scope.items;
    }
  }
});

In the modal controller, you can access the variable as a service.

controller('ModalInstanceCtrl', function ($scope, $modalInstance, items)

Assign the variable to a scope variable in order for it to be accessible in your modal template.

$scope.items = items;

Based on the website mentioned in the comment:

var ModalDemoCtrl = function ($scope, $modal) {
    $scope.open = function () {

    $modal.open({
        templateUrl: 'myModalContent.html',
        backdrop: true,
        windowClass: 'full',
        controller: function ($scope, $modalInstance, data) {
            $scope.data = data;
            $scope.cancel = function () {
                $modalInstance.dismiss('Close');
            };
        },
        resolve: {
            data: function() {
                // access outer controller scope by using $scope.$parent
                return $scope.$parent.data;
            }
        }
    });
};

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

What is the best method for extracting a value from a JSON file within an array using electron and node.js?

Hey there, I'm currently working with a JSON file that contains an array of value sets. I'm trying to figure out how to extract the first value from the initial set, specifically the value 3 under the key "pink". This is all being done in Node.js ...

Improving the pagination performance in AngularJS

I created an HTML template to showcase member details, along with adding pagination functionality to improve initial load time. Currently, I retrieve 15 members from the server at once and display them, allowing users to navigate through more members using ...

Utilizing AngularJS to Intercept Route Changes and Consolidate the Operational Logic

This question is related to another one: AngularJS - Determine if the view should be displayed by an ajax call result upon the route changes After finding a solution to my previous question, I have come up with the following code: (function() { &apos ...

Having trouble with Javascript not detecting when it's empty?

Recently, I have been attempting to modify the color of a submit button when a form is empty. As a beginner in this area, I am somewhat puzzled as to what mistake I might be making. I will share the current code with you in hopes of receiving some guidance ...

Unleashing the power of eventListeners through exponential re-rendering upon state updates

Trying to implement an eventListener for "keydown" to update the state (a boolean named showMenu). I placed it inside a useEffect, but it's not functioning correctly and I can't pinpoint the issue. When I include showMenu in the dependency arra ...

Copy files using grunt, in accordance with the ant pattern, while excluding any variable directories

My task is to transfer files from the src/ folder to the dist/plugin directory. Since the version can potentially change, I would like to exclude the version number in all instances. Here is what I currently have: files[{ cwd: 'src' src ...

Searching for a specific data point within the latest entry of a JSON file using Javascript

I am currently in the process of utilizing a sensor to measure temperature, which is then stored in a mongo database. This data can be accessed as a JSON file by visiting ('/data'). My goal is to determine the latest entry and extract the temper ...

What could be causing this function to work in Google Chrome, but not in Firefox?

For some reason, in Firefox, this section of the code never returns true. However, it works perfectly fine in Google Chrome. if(restrictCharacters(this, event, digitsOnly)==true) The expected behavior is that if a user inputs a number from 1 to 5 in the ...

$routeProvider - providing controller dependencies based on the URL path

Take a look at the following code snippet: var app = angular.module("app", [], function($routeProvider) { $routeProvider .when("/page1", { controller: "MyController" }) .when("/page2", { controller: "MyController" }) .when("/page3", { contro ...

What is the process for submitting and storing a collection of files in a database as a list?

I am trying to implement a feature in my MVC project where users can upload multiple files and see them listed before submitting the form. However, I am facing some challenges with finding a solution for this. Demo: My goal is to allow users to add multi ...

Is there a way to utilize javascript std input/output in repl.it effectively?

I created a straightforward program that calculates the factorial of a specified number, and I am interested in running it on repl.it. During its execution, I would like to interact with standard input and output through the command line. Is there a way ...

Is it possible to design a Controller and View that can manage the creation of one-to-many objects, specifically a single "container" object along with an unlimited number of "content"

One of the functionalities for users on the website will be the ability to create documents made up of chapters in a one-to-many relationship. Traditionally, this would involve creating separate views for chapter and document creation. How can I develop ...

Exploring the challenges of setting up Node in an attempt to unravel AngularJs 1.5

I recently started reading a book called "Unraveling AngularJS 1.5" in order to expand my knowledge on Angular development. Early on in the book, the author suggests installing Node.js, so I went ahead and did that. When I ran Node on the command prompt, i ...

What is the best way to create a deep clone of an XMLDocument Object using Javascript?

I am currently working on a project that involves parsing an XML file into an XMLDocument object using the browser's implementation of an XML parser, like this: new DOMParser().parseFromString(text,"text/xml"); However, I have encountered a situatio ...

Reactive Form value is not displaying in view because of FormControlName issue

I have successfully retrieved data from the database and need to pre-fill an update form with preset values. The issue I am facing is that when I add FormControlName to the input field, it removes the preset values. I have tried using setValue and patchV ...

NextJS rendering props in a loop

I need help figuring out how to render props in a loop using the forEach function. This is my current code: {console.log('the catalog inside the component ----->', catalog)} {Object.keys(catalog).forEach(key => { return ( <d ...

The variable req.body.username is not defined in the context of JavaScript

I am completely new to JS, Angular.js and node.js. I am currently working on a login-register project but facing a minor issue. Below is my code: login.ctrl.js: var app = angular.module('login-register', []); app.factory('UserLog', ...

Exploring Manipulation of M:N Associations in Sequelize

I have set up a sequelize schema using postgre DB export const Commune = sq.define("commune",{ codeCommune: { type: DataTypes.STRING(5), allowNull: false, primaryKey: true }, libelleCommune: { type: ...

Node.js redirection techniques

Node JS is still very new to me and I'm having trouble redirecting buttons to another page. Every time I attempt to redirect, I receive a "cannot GET /(the page that I am trying to redirect to)" error message. The code snippet I'm using for redir ...

Stunning Opening and Closing Animation with Ajax

Looking for help with creating an animation like the one shown here: Incorporating this into my current site at: dageniusmarketer.com/DigitalWonderland/ I want the window displaying text content to open and close as users navigate through the links, ess ...