Struggling with sending data to a modal in AngularJS?

I am dealing with the following code snippet

$scope.currentTask = undefined;

$scope.openModal = function (task, size, parentSelector) {  
    var parentElem = parentSelector ? 
                  angular.element($document[0].querySelector('.modal-demo ' + parentSelector)) : undefined;
    
    var modalInstance = $uibModal.open({
        animation: true,
        ariaLabelledBy: 'modal-title',
        ariaDescribedBy: 'modal-body',
        templateUrl: 'myModalContent.html',
        controller: 'homeController',
        controllerAs: '$ctrl',
        scope: $scope,
        size: size,
        appendTo: parentElem,
        resolve: {
            items: function () {
                return $scope.items;
            }
        }
    });

    $rootScope.currentModal = modalInstance;

    $rootScope.currentModal.result.then(function () {
    }, function () {
        $log.info('Modal dismissed at: ' + new Date());
    });
}

$scope.setTask = function(task) {
$scope.currentTask = task;
}

$scope.log = function (currentTask) {
console.log($scope.currentTask);
}
<div class="row" ng-init="processPages()">
<div class="panel panel-default col-xs-3" style="margin: 20px" ng-repeat = "list in pages[currentPage]">
<div class="panel panel-default">
<div class="panel-heading">
<h6 style = "float: right">({{list.tasks.length}})</h6>
<div class="panel-title">
<h4>{{list.name}}</h4>
</div>
</div>
</div>
<div class="panel-body">
<table class="table table-striped table-hover" ng-init = "tasks = list.tasks">
<tr ng-repeat="task in tasks">
<td ng-click="setTask(task); openModal(task);>
 <h5>{{task.name}}</h5>
</td>
</tr>
</table>
</div>
</div>
</div>

<script type="text/ng-template" id="myModalContent.html">
<div ng-init="editEnabled = false">
    <div class="modal-header" ng-init = "log(currentTask)">
        <h3 class="modal-title" id="modal-title" ng-show = "!editEnabled">Not editing</h3>
        <h3 class="modal-title" id="modal-title" ng-show = "editEnabled">Editing</h3>
    </div>
    <div class="modal-body" id="modal-body">
    <div ng-show="!editEnabled">

    </div>
    <div ng-show="editEnabled">

    </div>
    </div>
    <div class="modal-footer">
    <button style = "float: left" class="btn btn-primary" type="button" ng-show = "!editEnabled" ng-click="editEnabled = true">Editar</button>
        <button class="btn btn-primary" type="button" ng-click="ok()">OK</button>
        <button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
    </div>
</div>
</script>

This is how the page functions:

Initially, a list of tasks is displayed, and when one task is clicked...

...a model pops up.

I want to pass the task information to the model, but even though I set the task on the $scope before the model opens, the log function always prints that currentTask is still undefined. I have attempted changing the currentTask definition to be more concrete at the beginning, but then the log function prints the initial value rather than the updated value after the change.

Answer №1

The approach that finally solved my issue was to create a new controller specifically for handling the modal, and then establish a shared data communication pathway between the modalController and homeController using a service. The setup is functioning smoothly - below is the code snippet for the service:

var app = angular.module('agendaApp');

app.service('sharedModalProperties', function() {
    var task = undefined;
    var activeModal = undefined;

    return {
        setCurrentTask : function (task) {
           this.task = task;
        },

        getCurrentTask : function () {
            return this.task;
        },

        setActiveModal : function (modal) {
            this.modal = modal;
        },

        getActiveModal : function () {
            return this.modal;
        }
    }
});

Answer №2

The issue of the task being undefined suggests that the modal popup's ($scope) is not recognizing any corresponding model data. It seems to be generating a new scope object, causing your call to setTask() to fail as it is operating on the old scope. You may want to consider calling it within your modal display code.

$scope.openModal = function (task, size, parentSelector) {  
        var parentElem = parentSelector ? 
                      angular.element($document[0].querySelector('.modal-demo ' + parentSelector)) : undefined;

        var modalInstance = $uibModal.open({
            animation: true,
            ariaLabelledBy: 'modal-title',
            ariaDescribedBy: 'modal-body',
            templateUrl: 'myModalContent.html',
            controller: 'homeController',
            controllerAs: '$ctrl',
            scope: $scope,
            size: size
            appendTo: parentElem,
            resolve: {
                items: function () {
                  return $scope.items;
                }
            }
        });


        $rootScope.currentModal = modalInstance;

        $rootScope.currentModal.result.then(function () {
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        }

        //Include this code
        $scope.currentTask = task;
          //Alternatively, Call Set Task Here.
          setTask(task);

        );
}

Answer №3

After our conversation in the comments, you can try implementing something similar to this for your uibmodal's controller (Take a look at the changes I made on the GitHub repository)

...
$scope.items = ["items1", "items2", "items3"];
var modalInstance = $uibModal.open({
  animation: true,
  ariaLabelledBy: 'modal-title',
  ariaDescribedBy: 'modal-body',
  templateUrl: 'myModalContent.html',
  size: size,
  appendTo: parentElem,
  resolve: {
    modalItems: function() {
      console.log("items to send to modal", $scope.items);
      return $scope.items;
    }
  },
  controller: ['$scope', 'modalItems', function($scope, modalItems) {
    console.log("items sent to modal", modalItems);
    $scope.modalItems = modalItems;
  }]
});
...

HTML:

<script type="text/ng-template" id="myModalContent.html">
{{modalItems}}  <!-- This should display the array of items -->
</script>

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

Hide the burger menu when a link is clicked

Is there a way to make my Bootstrap burger menu automatically close when the user clicks on a menu link, rather than having to click on the burger itself? I've tried using some JavaScript code but it ends up disabling the burger menu entirely. Can any ...

Transform a numerical variable into a string data type

I am faced with a situation where I have a variable named val which is currently set to the number 5. Now, my goal is to update the value of val so that it becomes a string containing the character "5". Could someone guide me on how to achieve this? ...

unable to access various attributes in an angular directive

I have a particular HTML setup that effectively outlines each attribute's value through a distinct "attachment" directive. These values are located in the attrs list of said directive, which is within a modal file upload form. <p>For Testing Pu ...

Modify the `<link>` tag using the `onclick` function in JavaScript

I want to switch up the site's style with just a click on an icon <head> <meta charset="utf-8"> <link rel="stylesheet" href="styled.css" id="styles"> </head> Everytime I try to tackle th ...

The Gridsome website deployed on Netlify seems to be experiencing some issues. When clicking on links, the pages are not loading properly despite

After deploying my site on Netlify, I encountered an issue where the URL updates when clicking on links on the landing page, but the content does not show unless the page is refreshed. Interestingly, this issue does not occur on my local development server ...

Total number of goals scored by a single team (extracted from JSON data)

My data consists of football games in a JSON file [ { "game_id":"258716", "game_date_start":"2016-08-15", "season": "2016", "team_1_id":"119", "team_2_id":"120", "team_1_goals_quantity":"2", "team_2_goals ...

Utilizing Node.Js for Asynchronous Operations

I have a situation in my code where the Process1() function contains a database loop, causing Process2() and Process3() to be called multiple times. Which function from async should I use to properly wait for a for loop? async.waterfall([ function(ca ...

Attempting to retrieve the value of "id" using a "for...of" loop

I am seeking assistance with my auditTime function. In the loop using "for . . of", each element of the div HTML collection with the class name "time-block" should be iterated through, and the number value of that div's id should be assigned to the va ...

Basic asynchronous JavaScript and XML (AJAX) call

I am currently learning about ajax and experimenting with a script that involves extracting information from a JSON object and displaying it on the document. Below is an example of the JSON file named companyinfo.json: { 'id':1, 'name&apos ...

Difficulty accessing context.params query in Next.js Dynamic Path

I've almost completed setting up a dynamic page in Next.js using getStaticPaths(), but I'm running into an issue with the getStaticProps() function not referencing the URL query correctly to load the relevant information. Here is my code: //Get ...

The Oscillator node in the Web Audio API is unable to be started more than once due to an error

Every time I attempt to start, stop, and then start my oscillator again, I encounter the following error message: Uncaught InvalidStateError: Failed to execute 'start' on 'OscillatorNode': cannot call start more than once. Although usi ...

What could be causing the RTCPeerConnection icegatheringstatechange to not function properly?

I have been trying to utilize the icegatheringstatechange event handler, but it doesn't seem to be functioning properly. Is there a different method I can use to monitor changes in icegatheringstate? How can I determine when all ice candidates have be ...

Mastering the art of reading rows in ASP.NET using Java Script

Within the code snippet below, you'll find an image located in the second column. Clicking on this second column should allow me to access the data stored in the first column. Let's say we have a table with 10 rows. If the user clicks on the ico ...

How can we have a div stay at the top of the screen when scrolling down, but return to its original position when scrolling back up?

By utilizing this code, a div with position: absolute (top: 46px) on a page will become fixed to the top of the page (top: 0px) once the user scrolls to a certain point (the distance from the div to the top of the page). $(window).scroll(function (e) { ...

Avoiding external variable reference through Jest.mock

For snapshot testing, I need to create a simple dummy mock of 1 react component. When attempting to use React.Component within the mock function, an error is thrown: The second argument of jest.mock() cannot reference external variables. However, usin ...

New solution for Java applet requiring communication with browser using JavaScript

Within our web platform, we have been utilizing a Java applet to interact with the MS Word application using jacob jar. This allows users to open, edit, and automatically upload files to the server upon saving. However, due to Google Chrome discontinuing ...

jQuery click event not working post Ajax request returned a 403 error

I am facing an issue with my ajax request where I receive a 403 error message. Strangely, when this error occurs, the click() function associated with the ajax call stops working. There is no manipulation of HTML elements before or after the ajax call, and ...

What is causing the error when using Interfaces and Observable together?

I created a ToDoApp and integrated Firebase into my project, but I am encountering an error. ERROR in src/app/todo-component/todo-component.component.ts(25,7): error TS2740: Type 'DocumentChangeAction<{}>[]' is missing the following proper ...

Is it possible for image.src to pose a security threat?

Here is the code snippet I am working with: var image = new Image(); image.src = "https://MyTrackingSite.com/?myTrackingParameter=whatever" I noticed that the image is not added to the DOM tree. Is it still rendered by the command "image.src"? Could this ...

Ways to showcase the chosen image from the input field?

Can someone help me with an issue I'm having regarding displaying selected images? Every time I try, I encounter this error message: Not allowed to load local resource: Any suggestions or insights into why this might be happening? <input type=&a ...