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

Utilizing Ajax: Sending Customized Data to a Modal

Having never worked with jquery before, I struggled to find a solution for my specific case. On the cockpit.php page, I have a form that retrieves content from a mysql database. Currently, I am able to display this content in a div on the same cockpit.php ...

Utilizing the indexOf Method in AngularJS

Here is my array: emp=["111","56"]. This is the code I have: <input type="text" placeholder="Enter" class="form-control" name="Emp" ng-model="myModel.Emp" ng-required="currentStep ==2"/> <input type="text" placeholder="Enter" class="form-contro ...

Output the result of a PHP script inside a JavaScript code

I'm having trouble getting the code below to display the success word. Can anyone spot what's wrong with it? Appreciate any help in advance. <script type="text/javascript"> function verification(){ var s = document.test_form.textfiel ...

Keep track of the user's email address as they complete the form

I currently use a Google Form to gather information from employees who work in remote locations Emp No * Punch * Customer details / mode or travel All the data collected is stored in a Google spreadsheet structured as follows: Timestamp Emp No Punch ...

Exploring the compatibility of Husky with Typicode using Yarn

Currently, I have implemented the use of husky to configure git hooks for prettier. However, I am facing a persistent issue whenever I attempt to commit or push: > husky - Can't find npm in PATH. Skipping precommit script in package.json My curre ...

What is the most efficient way to iterate through an array to push properties into an object nested within another array?

I have been working on a small Angular application that functions as a scheduler, allowing users to input a Name, Start and End dates, and toggle a boolean checkbox through a form. One challenge I am facing is trying to assign the names entered by each use ...

Setting a condition for a function call when a checkbox is clicked

My table has columns labeled NoBill and Bill, with checkboxes as the values. Here is the default view of the table: https://i.stack.imgur.com/ZUvb2.png When the checkbox in the NoBill column is clicked, the total value (this.total) is calculated. The t ...

Tips on capturing a URL using JQuery

Currently, I am in the process of importing an external HTML file into my webpage. Within this file, there is a JavaScript method linked to a form submission event. function ValidateInput(){ //some code if(validationFailed){ ...

Ensure that text is aligned alongside an image only when both elements are enclosed within <p> tags

When using an API to pull markdown content from Contentful and converting it to HTML with ReactMarkdown, a common issue arises. The resulting HTML structure often places the text content in separate paragraphs such as: <p>Some text content</p> ...

Textarea not displaying default values when ng-model is applied

My Angular application includes a textbox in the following format: <div class="panel-body text-center"> <textarea id="mytext" class="form-control" rows="4">John,2 Jane,3 John,4 Jane,5 </textarea> </ ...

implementing a SetTimeOut function following the clicking of a button

Hey there, I've been working on a code snippet that switches the display state from block to none with an onClick function. However, I'm looking to add a delay before the state change happens so that there's time for an animation effect to ...

Tips for Storing Your Data Collection: A Guide on Different Storage Options

In the different parts of my app, I require access to a dataset containing timezones. Traditionally, I have stored such data in a class method like Timezone.all_zones (Ruby) for easy accessibility anywhere in my code. Is there a way to achieve this same ...

Issue encountered during rootScope update

I've encountered an issue with my Angular service that updates the $rootScope. The actual updating process works as intended, but it triggers an error in the console that has me concerned. app.service("scroll", function($rootScope, $window) { this ...

Interactive font-awesome icons within an interactive dropdown menu

I am currently facing an issue with using two Fontawesome icons in a clickable dropdown menu. The dropdown menu does not toggle when I click on the icons directly; however, it works when I click on the padding around them. The example provided by W3schools ...

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? ...

The background image fails to display properly on the server in Next.js

Hello, I'm currently using NextJs and I have a challenge. I want to set a background image on the body element that is rendered server-side. Below you'll find my code snippets: First, here is my App.js: import BodyStyle from '@components/Bo ...

Using cannonjs and Three.js to connect a physics body with a visual mesh

I have written the code below to create two spheres using cannonjs with Three.js for rendering. var world, mass, body, shape, timeStep=1/60, camera, scene, renderer, geometry, material, mesh; initThree(); initCannon(); animate(); func ...

`Write a custom AngularJS directive`

I followed the official AngularJS documentation to implement this directive. However, I am facing an issue with setting validity using the $setValidity() method in the link function of my directive. The changes are not reflecting in the view when I try to ...

How to transition from using a CDN to NPM for implementing the Google Maps JavaScript MarkerClusterer?

Currently integrating Google Maps JavaScript MarkerClusterer from CDN, I am considering transitioning to the NPM version for Typescript checking in my JavaScript files. However, I am encountering difficulties understanding how to make this switch. The docu ...

Sharing $scope Data Between Controller and Directive in AngularJS

Recently, I created a straightforward directive that displays an object: var app = angular.module("myApp", []); app.controller('myCtrl', function($scope) { $scope.users=[ {name:'davidi',age:'23'}, {name:'karen ...