Utilizing AngularJS scope within a modal viewport

I am encountering an issue with my simple controller while fetching and displaying messages using $http.get in HTML using ng-repeat. The problem arises when trying to access the messages from a modal window, as it always prints the first message only.

index.html

 <div ng-controller="MessageController as ctrl">
    <ul class="list-group" ng-repeat="message in ctrl.messages">
        <li class="list-group-item">
            {{message.title}}
            <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal">
               Edit
            </button>

            <div class="modal fade" id="myModal" aria-labelledby="myModalLabel">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">

                        <div class="modal-body">
                            {{message.title}}
                            <label>Title:</label><input ng-model="message.title"/>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                            <button type="button" class="btn btn-primary">Save changes</button>
                        </div>
                    </div>
                </div>
            </div>
        </li>
    </ul>

</div>

app.js

var app = angular.module('plunker', []);
var prefix = 'http://jsonplaceholder.typicode.com';
app.controller('MessageController', ['$http', function ($http) {

var $this = this;
$http.get(prefix + '/posts').success(function (response) {
    $this.messages = response;
    return response;
   });
}]);

Here's the plucker http://plnkr.co/edit/ZKyZJV9aYD5AU6kmsMTC?p=preview

Answer №1

The issue arises when the same id, id="myModal", is utilized for all modals. In such cases, the search on HTML will terminate after locating the initial match, resulting in the repeated display of the same modal.

To resolve this, consider employing a variable id by incorporating $index from within ng-repeat.

id="myModal_{{$index}}" 

Apply this adjustment to both divs (the id and data-target) to ensure proper functionality.

Answer №2

this is effective:

<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal{{$index}}">
...
<div class="modal fade" id="myModal{{$index}}" aria-labelledby="myModalLabel">

http://plnkr.co/edit/vXbN1FwH4yjb66rLV5qn?p=preview

However, using #id for addressing elements is not recommended in angular development

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

Angular 6 throws an error stating: "The property 'push' cannot be read of null."

The Cart model is defined as follows: //declaring a cart model for products to add export class Cart{ id:string; name:string; quantity:number; picture:string; } Below is the code for my app.service.ts: import { Injectable, Inject } fro ...

What techniques work well for managing permission tiers within the MEAN stack environment?

Following the insights from the book "MEAN Machine", I successfully implemented a basic token-based authentication system that restricts access to certain model data to authenticated users. Now, I am eager to enhance this system by introducing three disti ...

Why isn't the field I added to my state functioning properly?

Can anyone explain why I am getting names without the added selected field??? I can fetch names from my API JSON (1) and I'm attempting to modify it by adding the selected field (2). export default function Display() { ... const init ...

What is the process for configuring SSL in node.js and express.js?

I'm currently working on setting up my application to run in HTTPS mode. Despite thinking that my configuration is correct, the page isn't loading at all. Within my SSL folder, I have the following files: credentials.js my-ca.pem my-cert.pem my ...

How can I access the parent elements within a recursive directive?

I'm currently implementing a recursive directive called https://github.com/dotJEM/angular-tree to iterate through a model structure like the one below: $scope.model = [ { label: 'parent1', children: [{ ...

Utilizing Vue components to streamline the process of adding and updating data

I have a rather straightforward parent/child component. I am looking to utilize the child component in two ways - first, for adding a new entry and second, for updating an entity. Here are the components that I've built: https://codepen.io/anon/pen/b ...

What is the best way to check the difference between the current date and time with another date and

Seeking assistance in comparing 2 dates using JavaScript has been a bit challenging for me. I haven't found the exact solution on this platform yet. As a beginner in JavaScript, I initially assumed that obtaining the current date and time would be a s ...

A different approach to fixing the error "Uncaught (in promise) TypeError: fs.writeFile is not a function" in TensorFlow.js when running on Chrome

I've been attempting to export a variable in the TensorFlow posenet model while it's running in the Chrome browser using the code snippet below. After going through various discussions, I discovered that exporting a variable with fswritefile in t ...

Implementing a filter function in Angular 2 and Ionic 2 that is dependent on *ngFor on a separate page

I recently created a simple ion-list along with a filter to display items based on a specific key:value pair. I'm not entirely sure if I've implemented it correctly, so any suggestions on a better approach would be greatly appreciated. LIST.HTML ...

pop-up window that shows chosen choices using javascript or ajax

I have a specific HTML code that allows users to select multiple options. I would like these selected options to be displayed in a popup or a div in real-time as the user makes their selections. I have attempted using a selectbox with checkboxes, but extra ...

Utilizing Cookies within an HTML Page

My current code is functioning perfectly, accurately calculating the yearly income based on the input "textmoney." I have a link to a more advanced calculator for a precise prediction. My goal is to find a way for the website to retain the data input from ...

iterating over a nested map within a map in an Angular application

I wrote a Java service that returns an observable map> and I'm currently struggling to iterate through the outer map using foreach loop. [...] .then( (response: Package) => { response.activityMap.forEach((key: string, value ...

What is the level of visibility in Nextjs?

Is it safe to expose the sources of files located in the 'pages/' directory? For instance, if you set up a page specifically for administrators at pages/admin and restrict access through Middleware, does this enhance security measures? ...

It appears that my array is not being properly populated by my callback functions

I am encountering an issue with my callback functions. The objective of my code is to send 16 GET requests to a REST API in order to retrieve 16 distinct JSON files. These JSON files are then supposed to be converted into dictionaries representing the foot ...

`Vue Component failing to display data from Blade File`

In my project using Laravel Blade, I am currently in the process of converting some blade files to Vue components. One challenge I encountered is trying to display a dynamically created page title on the screen from the Vue component rather than the blade ...

Struggling to implement my reusable React component within a React Bootstrap modal

I have developed a reusable textarea React component: import React from 'react'; import '../form-input/form-input.styles.scss'; const TextAreaComponent = ({ handleChange, label, ...otherProps }) => ( <div className="group"> ...

Having trouble getting the .toggle() function with classList to work on one element, despite working fine on others

I've been struggling to apply a class to an HTML element when I click on another element of the page. Despite numerous attempts, it just doesn't seem to work for me. Let's take a look at my code: HTML Code: <div class="container&qu ...

Transform a span into a div while retaining its content and styles, ensuring compatibility with Internet Explorer

Is there a reliable JavaScript method to convert a span into a div while preserving its contents and the original classes of the span? The classes are pre-set, so hardcoding should be possible. <span class="my class"> <p class="conten ...

Create a unique key dynamically based on a specified scope value using AngularJs

I am working with an angular directive that utilizes a title with a key from a messages.properties file. To dynamically generate the key, I want to concatenate 'root.' + scope.value + '.title' like so: titre="{{ 'flux.' + &ap ...

The console is displaying a null value outside of the block, however, the correct value is returned when

I am having an issue where the first console.log() is not returning the correct value, but the second one is. Can anyone provide assistance with this problem? angular.module('resultsApp', ['ngCookies']) .config(['$qProvider&a ...