``How can I effectively handle and display Angular JSON text in an alert message?

Is there a way to pass a JSON entry into the onClick event for triggering an alert box in AngularJS?

I'm attempting to display a message box with the content of a specific JSON entry when clicking on a row within a table. The issue seems to be isolated to this particular section as the rest of the table functions correctly.

<tr ng-repeat="x in json.tags | filter:filterName | filter:filterID | orderBy:myOrderBy:reverse" onClick="alert(x.AlertInfo)">

Below is the complete source code.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>

<div ng-app="myApp" ng-controller="getJson">  
   <!-- <p>Status : {{statuscode}}</p>
    <p>StatusText : {{statustext}}</p>-->
    <input type="text" id="input" ng-model="filterName" placeholder="Search.." title="Type in a name">
    <table id="myTable">
        <tr>
            <th ng-click="orderByMe('t1')" width="8%">t1</th>
            <th ng-click="orderByMe('t2')" width="5%">t2</th>
            <th ng-click="orderByMe('t3')" width="3%">t3</th>
        </tr>
        <tr ng-repeat="x in json.tags | filter:filterName | filter:filterID | orderBy:myOrderBy:reverse" onClick="alert(x.AlertInfo)">
            <td>{{x.t1}}</td>
            <td>{{x.t2}}</td>
            <td>{{x.t3}}</td>
        </tr>
        </table>
</div>

<script>
    var app = angular.module('myApp', []);
    app.controller('getJson', function($scope, $http, $interval) {
        $scope.getData = function() {
            $http.get('http://JSONGET').
                then(function(response) {
                    $scope.statuscode = response.status;
                    $scope.statustext = response.statusText;
                    $scope.json = response.data;
                    console.log('Fetched data!');
                });
         };

         $scope.orderByMe = function(x) {
            $scope.myOrderBy = x;
         };

         $scope.intervalFunction = function(){
            $scope.getData();
            $interval(function(){
                $scope.getData();
            }, 15000);
         };

         $scope.intervalFunction()        

    });
</script>

Answer №1

Instead of directly calling alerts and consoles in HTML, you can assign the alert to a scope function in the controller.

$scope.alert = window.alert;

Now you can call the alert from the HTML using ng-click instead of onClick.

<tr ng-repeat="x in json.tags | filter:filterName | filter:filterID | orderBy:myOrderBy:reverse" ng-click="alert(x.AlertInfo)">

Answer №2

Utilize the $window service along with ng-click. The alert will always function in ng-click, but if you need to manipulate some data.

app.controller('retrieveData', function($scope, $http, $interval, $window) {
   // content and methods
   // ...
   // ...
   $scope.displayAlert = function(index) {
       var objectData = $scope.data[index]; // data of the selected table-row
       $window.alert(objectData.AlertInfo); // possibility to manipulate, convert object to string or perform desired actions
   });
});
<tr ... data-ng-click="displayAlert($index)">
   ...
</tr>

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

How to Incorporate an Anchor Link into a Div as well as its Pseudo Element using CSS, Javascript, or jQuery

How can I make both the menu item and its icon clickable as a link? When either is clicked, the link should work. Here is a CodePen example: http://codepen.io/emilychews/pen/wJrqaR The red square serves as the container for the icon that will be used. ...

Transmit the JSON Data file through an AJAX request

I am encountering an issue where the HttpPostedFileBase is null when trying to send an image file to a Controller. I have attempted entering image: image outside of JSON.stringify({}), but it did not work. Additionally, I tried changing the contentType f ...

Retrieve JSON data from PHP using D3.request

Looking to extract data from an SQL database using PHP and then convert it into JSON format with the "echo json_encode($array);" function. I have a requirement to create a graph using D3.js, which means I need to transfer this JSON data from PHP. Can anyo ...

Tips for avoiding the need to reload a single page application when selecting items in the navigation bar

I am in the process of creating a simple Single Page Application (SPA) which includes a carousel section, an about us section, some forms, and a team section. I have a straightforward question: How can I prevent the page from reloading when clicking on nav ...

Using AJAX and React to handle RESTful requests

Hello there, I am attempting to utilize a web service in React but am encountering issues with the AJAX function. I'm unsure if my code is working as expected. Here is a snippet of my code: prox= {"email":email, "password": password}; //tag comment $ ...

The `.append()` function includes HTML content as plain text

I am using JavaScript to dynamically add HTML elements to my webpages. I have created a loop that iterates through all the projects, each containing multiple pictures. The first step involves generating the project title and adding it within a div element ...

Using Angular and Jasmine: techniques for simulating a service that provides a promise

In my AngularJS application, I have a controller called MenuCtrl that utilizes a service provided by "$mdSidenav" from Angular Material. This service is created using a factory method. angular.module('leopDirective', []) .controller('Me ...

axios does not distinguish between response and error in its return value

I have created a React component that contains a function called onFormSubmit. This function calls another function from a separate component, which in turn makes a POST request using axios. I want the ability to return a response if the POST request is su ...

MUI Grid with Custom Responsive Ordering

Can I achieve a responsive grid layout like this example? Check out the image here I have already coded the desktop version of the grid: <Grid container spacing={2}> <Grid item sm={12} lg={6} order={{ sm: 2, lg: 1 }}> ...

Angularjs application and bash script generating different SHA256 hashes for the same file

In my AngularJS app, I am struggling to get the digest of an uploaded file. The issue is that the resulting hash is not matching the one obtained using bash locally. Initially, I used jshashes, but when I noticed discrepancies in the hashes generated by t ...

Retrieve JSON information from a database using an API to showcase additional outcomes

I am currently developing an iOS application that needs to fetch and display data from a MYSQL database. I have set up an API to establish communication between the app and the database. The database is sending valid JSON, as shown below: [{"name":"Mauric ...

Organizing JSON objects into groups of x items

I am working with dynamically generated JSON data that needs to be grouped by a specific number. I have a method for generating the variable representing the grouping number, but now I need to organize the items based on that number. Here is the original J ...

AngularJS efficiently preloading json file

I am just starting to learn about angularJS. Apologies if my question is not very clear. Here is the problem I am facing: I have a JSON file that is around 20KB in size. When I attempt to load this file using the 'factory' method, I am receivin ...

Modifying the display property of an element using JavaScript

Hello, I'm encountering an issue with a section of my javascript code. I am attempting to make the #showAddress element display as block when the deliverservice radio button is clicked or checked. I have tried searching for solutions on Stack Overflow ...

Create a new array by dynamically generating a key while comparing two existing arrays

One of the features in my app involves retrieving data from an API and storing it in $scope.newz. The previous user activity is loaded from LocalStorage as bookmarkData. I am facing a challenge with comparing the contentId values in arrays $scope.newz an ...

Tips for displaying negative numbers as positive in AngularJS

After fetching data from the server using $http.Get, I have a function that calculates the total value. The total value comes out as negative (-370), which is correct. However, when I try to use this value to create an angular chart, I need to display it a ...

Encountering an issue with parsing JSON using Retrofit and GSON, faced errors while attempting to parse and retrieve callback data

I am utilizing Retrofit to manage Calls to my API for an Android Application. My goal is to have Retrofit handle the parsing of JSON and create a list of Objects based on the POJO I developed. The error message I encountered is "com.google.gson.JsonSyntax ...

Diminishing sheets in the realm of C# web application development

I have been researching ways to incorporate a fading page function, but I am encountering some issues. I am unsure about the specific code that needs to be included in jquery.js and how to integrate this script into all of my web forms or alternatively int ...

Using the power of jQuery, execute a function only once when the element is clicked

My goal is to use jQuery's .one method to change the color of an element only once, even if clicked again. However, I am having trouble getting it to work properly. Here is my HTML: <!DOCTYPE html> <head> <meta charset="UTF-8"& ...

Change the image size as you scroll through the window

While my opacity style is triggered when the page is scrolled down, I am facing an issue with my transform scale not working as expected. Any suggestions on how to troubleshoot this or any missing pieces in my code? Codepen: https://codepen.io/anon/pen/wy ...