Unable to retrieve $scope within a dynamic $route in an AngularUI modal

In my AngularJS test app, I've encountered an issue with loading a modal window dynamically using AngularUI. Although the modal windows load successfully, the $scope variables in the modal controller are not being accessed by the template, and I'm unable to trigger any $scope functions from the template.

For reference, here's the link to the plunkr showcasing the problem: Plunkr

Take a look at the $routeProvider configuration:

.config(function($routeProvider) {
  $routeProvider
    .when('/page/:name', {
        templateUrl : 'modalContainer',
        controller : 'ModalCtrl'
    })
 })

Additionally, here's the code for the ModalCtrl controller:

.controller('ModalCtrl',['$scope', '$modal', '$route', function($scope, $modal, $route) {

    console.log("hello I am the ModalCtrl") //This console log runs

    var modalInstance = $modal.open({
        templateUrl : 'modal.html',
    });

    $scope.activity = $route.current.pathParams.name;
    console.log($scope.activity) //This console log runs & shows the correct value,
                                 // but the $scope variable is not visible in the template

    //Modal controls
    $scope.close = function () {
        console.log("close!") //This does not run.
        modalInstance.close();
    };

}]);

It seems like there might be an issue with how I'm setting up the scope for the modal window. Can anyone spot where the problem lies?

Answer №1

To make the modal window functional, it is necessary to set up a controller that can access the $scope variable. The following code demonstrates how this can be achieved:

var modalInstance = $modal.open({
    templateUrl : 'modal.html',
    controller: 'ModalCtrl'
});

var ModalCtrl = function ($scope, $modalInstance) {
    //Control logic for the modal
    $scope.close = function () {
        console.log("Closing modal!") //This message will be displayed
        modalInstance.close();
    };
}

Answer №2

Make sure to include the scope parameter when opening a modal, as shown below:

var modalInstance = $modal.open({
    templateUrl : 'modal.html',
    scope : $scope
});

If you do not pass the scope parameter, the modal window will use $rootScope.new() instead.

Additionally, remember to remove the ng-controller attribute from your template.

<script type="text/ng-template" id="modalContainer">
    <div></div>
</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

Using a jQuery function to pass a value through $_GET parameters

I am trying to pass a dropdown value using $_GET with the help of a jQuery function This is the code I have written: <div class="span2 text-right"> <label class="f-s15">Choose Exam to take:</label> </div> <div class="span3" ...

Retrieve data depending on the conditions set in the if statement

I am currently working on a demo app that retrieves data from the Chuck Norris jokes API. I have included a variable in the endpoint to specify the joke category. fetchJoke: function() { fetch( `https://api.chucknorris.io/jokes/random?category=${th ...

Sort the elements in the array by a specific value using the orderBy

Within my code, I am utilizing nested ng-repeat to retrieve data from the server: <div ng-repeat="x in result | filter:sellbox " > <div ng-repeat="z in x.data | orderBy:'??' " > {{x.rate_type}} to {{x.nam ...

Combine collapse and popover in Bootstrap 3 for enhanced functionality

I'm facing some issues trying to use the badge separately from the collapse feature. $(function (e) { $('[data-toggle="popover"]').popover({html: true}) }) $('.badge').click($(function (e) { e.stopPropagation(); }) ) Check o ...

Focus Google Map on Selected Option using AngularJS

I'm attempting to center the map based on a selection in a drop-down select option box. Despite trying various examples, I haven't been successful in getting the map to recenter to the new latitude and longitude coordinates. I'd like to ach ...

Access the URL parameter in react-router and incorporate it into the Component

I need to retrieve the id parameter from the URL in my react-router setup (App.js): import React from "react"; import ReactDOM from "react-dom"; import Main from "./ui.js"; import Master from "./master.js"; import FireCess from "./FireCess"; import { ...

Using ng-repeat in conjunction with the OpenWeatherMap API to search for and display cities

Hey everyone, I've been attempting to organize data retrieved from openweathermap.org using the provided API and AngularJS's ng-repeat feature. Unfortunately, I am facing some challenges in making it work properly. My goal is to initially display ...

Execute a POST request using Puppeteer

Currently, I am experimenting with JS+Puppeteer to create a script for adding items to the cart on a website. Due to heavy traffic, the website often crashes, so I want to bypass traditional clicking methods and instead send item information directly to th ...

What is the reason that server.js is always excluded from the Webpack build process?

I am currently utilizing Vue.js 3 for the front end of my application, while employing Node/Express for the back-end. My goal is to implement server side rendering, but I have encountered some challenges along the way. As far as I can tell, the client-sid ...

What is the best way to incorporate a random JSON section into a JSON structure?

Let's say I have a JSON message: json_msg = [{ LOG: 'TPT', TYPE: 'UPDATE', UIN: 'VEHICLE', SEQ_NO: 20129, VALUE: 1, TIMESTAMP: 518342.438263017, EXPERIMENT: 0, IDENT: '.Model.Index_obj.MuLifeCycle_ob ...

D3 with Y-axis flipped

After creating a bar plot, I noticed that my Y axis is reversed and the scale seems off. I've been struggling to figure it out on my own. Here's a link to the Jsfiddle with the code. If you want to give it a shot somewhere else, here is the code ...

Sorting Angular orderBy with primary field importance

Building upon a previous inquiry about ordering multiple fields in Angular, I am now curious about the possibility of achieving a similar result. Specifically, I am looking to order by multiple fields while prioritizing one field if its value is not null. ...

What is the best approach for handling an AJAX request on the server side?

Consider the function below: $.ajax({url:"http://127.0.0.1:8080", data: "123", success: function(response, textStatus, jqXHR) { alert(response); }, error: function(jqXHR, textStatus, errorThrown) { alert("An er ...

"Use jQuery to select all the cells in a row except for the

I found a visually appealing table layout that looks like this : https://i.stack.imgur.com/oRxYP.png What caught my attention is how clicking on a row selects the entire row. Take the example in the image above, where the second row is highlighted upon s ...

Error in ReactJS: Attempting to access property 'preventDefault' of an undefined value

Looking to implement a simple onClick event/function in ReactJS. Upon clicking the button, I intend to execute a function named "onClick", but I encounter this error message in the console: app.js:62 Uncaught TypeError: Cannot read property 'prevent ...

Angularjs: Removing unique characters from a string

What is the best way to remove a hyphen from a string in order to just keep the letters? For example, if I have the string "-KTxEMxrAY", how can I eliminate the hyphen and obtain "KTxEMxAY"? I am utilizing AngularJS for this task. ...

How can I show the most recent x floating point values on a chart using ChartJS?

I'm currently working on a Vertical Bar Chart using react-chartjs-2. I have an array of numerous float numbers saved. My attempt to utilize the chartjs callback option to only show the last value on the graph failed. The problem lies in the fact th ...

Creating a class dynamically in Angular 2 Typescript based on a property value

How can I dynamically assign classes in HTML based on a property in Angular 2 without using jQuery or Bootstrap? I am trying to open a dropdown list. Here is what I have: <li class="dropdown mega-menu mega-menu-wide" //stuck at adding class of op ...

Tips for automatically closing an accordion tab when a different one is clicked

I've created a unique accordion that allows me to assign a color class to the opened item. However, I'm looking to add a new feature where only one tab remains open at a time, automatically closing any others when clicked. Below is my current co ...

Tips for providing input to an angular controller

As someone new to AngularJs, I have experience with KnockoutJs and its MVVM methodology. In KnockoutJs, you define data in the ViewModel and use data binding to connect it to the View, allowing for the creation of modular and reusable controls that display ...