What is the best way to insert dynamic data into a modal?

I am currently facing an issue with passing a dynamic scope variable into a modal window. The problem arises when I try to update the variable while the modal is open. At present, I send the data to a controller when the modal opens:

    scope.open = function (roomname, image) {
        console.log("clicked modal");

        console.log("roomName: " + roomname);
        console.log("image: " + image);

        scope.imageContents = image;
        console.log("scope.imageContents: " + scope.imageContents);


        scope.modalInstance = $modal.open({
            animation: scope.animationsEnabled,
            templateUrl: 'tpl/modal-template.tpl.html',
            controller: 'ModalInstanceCtrl',
            resolve: {
                items: function () {
                    console.log("scope.imageContents in resolve: " + scope.imageContents);
                    return scope.imageContents;
                },
                compassHeading: function () {
                    console.log("scope.imageContents in resolve: " + scope.compassHeading);
                    return scope.compassHeading;
                }
            }
        });
    };

and in my controller:

angular.module('TestApp').controller('ModalInstanceCtrl',function ($scope, $modalInstance, items, compassHeading) {

    'use strict';

    $scope.items = items;
    $scope.selected = {
        item: $scope.items
    };
    $scope.compassHeading = compassHeading;

});

The compass Heading variable is constantly being updated, so I am trying to get the compassHeading variable to show these changes in the modal.

Answer №1

If you're looking to streamline your code and easily manage variables, consider utilizing a service that contains your variable as well as any other necessary variables:

angular.module('TestApp')
    .service('TestService', [function () {
        return {
            model: {
                'compassHeading': null
            }
        };
    }]);

In your main controller, you can access the service like this:

angular.module('TestApp')
    .controller('MainController', ['$scope', 'TestService', function ($scope, testService) {
        $scope.model = testService.model;
        ...
    }]);

The same approach can be used in your modal controller:

angular.module('TestApp')
    .controller('ModalInstanceCtrl', ['$scope', 'TestService', function ($scope, testService) {
        $scope.model = testService.model;
    }]);

To update the value of compassHeading, simply assign a new value using

$scope.model.compassHeading = <some_value_here>;
.

It's worth noting that changes made to compassHeading outside of the controllers will also be reflected inside the controllers, thanks to the reference nature of the model object within the service.

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

Exploring the usefulness of `bind(this)` within a ReactJS constructor

I have a good understanding of the Javascript function bind. However, I'm puzzled by why in the React.js snippet below, this is being bound again to itself. Is this related to the constructor, as this in the constructor can vary depending on how it&ap ...

Encountering a d3.js runtime issue following the transition to Angular 8

I've been experimenting with upgrading my Angular 6 application to Angular 8. It compiles fine, but I'm facing a runtime error as soon as it runs: "d3.js:8 Uncaught TypeError: Cannot read property 'document' of undefined". The specific ...

Utilize Reactjs to efficiently showcase a collection of arrays within an object

I am struggling with a JSON file that has nested dropdown mega menu levels and I can't figure out how to map and render multiple levels of arrays and objects to create a tree-like structure. Here is my current JSON Structure: { "megamenu": [ { ...

Silhouettes dancing across handcrafted designs

I have been trying to create a custom geometry using vertices and faces, but I am facing an issue where the geometry does not cast shadows on itself and the faces all have the same color as it rotates. I have attempted various solutions but haven't ha ...

Add HTML content dynamically to a layout that is connected to a controller

While I may not have the proper heading for this question, I need to add this piece of HTML dynamically to my layout and attach its click events with a controller. <div id="subscriber1" class="participant-video-list"> <div class="participant- ...

Error encountered while using Jest, React, Typescript, and React-Testing-Library

I have set up a project using React/NextJS with Typescript and now I am incorporating unit testing with Jest and React Testing Library. One of the unit tests for my component is as follows: import React from 'react'; import '@testing-libra ...

Replicating radio button functionality using buttons in an HTML document

I am attempting to simulate radio button behavior using normal buttons for a quiz application. Currently, my code is working as intended and permanently highlights buttons with the desired color. However, I want all other buttons in a question to be white, ...

Error: Unable to assign a value to the 'name' property of an undefined object after modifying input field data

I am currently working on developing a React application. The app includes a button labeled "Add" that, when clicked, adds multiple input fields to the screen. Each line of inputs also features a button marked "X" which allows users to remove that specific ...

Is there a way to display my current connected clients to a new client using socket.io?

I am currently working on a project involving socket.io. Upon connecting to a new socket, my input username is displayed in the "usersDiv" where all clients are supposed to be listed. However, I've noticed that when I open another tab and input my nam ...

Paragraph Separated by Bullets Without Bullets At End of Line

I need assistance in creating a unique type of list that I call a "bullet separated paragraph list" by using a javascript array of strings. For example: item • item • item • item • item     item • item • item • item item • ...

I am having trouble combining my streams with es.merge

Here is the gulp task that I am working on: var es = require('event-stream'), concat = require('gulp-concat'), templateCache = require('gulp-angular-templatecache'); var scripts = gulp.src(paths.js + '/**/*.js&a ...

Adjusting the navigation image as it passes through various div elements during scrolling

Is it possible to dynamically change an image in the navigation bar based on the user's scroll position? For example, I want pic1 to be displayed when the page content is at the top, then switch to pic2 once the user reaches the footer, and then back ...

Having trouble getting Owl Carousel to function properly within an AngularJS partial view?

I just started working on a single page application using AngularJs. Here is a snippet from my Index.html: <!DOCTYPE html> <html data-ng-app="myApp"> <head> <meta charset="utf-8> <meta name="viewport" content="width=devi ...

Organize elements from an array in a clockwise manner into a container based on a boolean

I'm currently developing a visual card game and facing the challenge of organizing the seating arrangement for players around the table. The priority is to assign the player's ID, with the boolean "pov" set to "true," to the bottom container with ...

Using Vue.js to inject plain text into a Vue component from HTML

I am currently in the process of transitioning code from ASPX to VUE.JS. In the previous system, there was a feature that allowed plain text to be injected into HTML (such as messages with text, images, links, and inputs). However, in VUE, the injected HT ...

Steps to choose a div element from an Ajax Response utilizing Prototype JS

I attempted to use the code below, but unfortunately I have not been able to achieve success yet. var myAjax = new Ajax.Request( url, { method: 'post', onException: function (xhr, e) { alert('An e ...

Retrieving table information using javascript

My goal is to retrieve information from the <td> elements within the following HTML table: <table class="datadisplaytable" summary="This table lists the scheduled meeting times and assigned instructors for this class.."> <caption class="cap ...

Switching code from using .hover() to using .click() while still maintaining the functionality of both.orChanging code to switch

How can I change this script to trigger on click and also maintain the hover functionality: $x = jQuery.noConflict(); $x(document).ready(function () { $x(".swatch-anchor").on('click hover', function () { var newTitle = $x(this).attr( ...

Utilize Angular to enclose columns within rows for optimal organization

Updated with angular code snippet (for demonstration purposes only) I have been exploring ways in AngularJS to automatically wrap columns into rows after a certain number of columns while keeping the index intact. <div class="row"> {{for (var i = 0 ...

Switching from hover to click on the menu

I am struggling with adjusting the function to trigger on 'click' instead of 'hover'. I have attempted changing 'hover' to 'click' and using 'toggle' but have not seen any positive outcomes. $('#menu ...