Angular click event not functioning properly on elements loaded via http request

Check out my CodePen link: http://codepen.io/gauravcoder/pen/vLWEjJ?editors=101 I'm just getting started with Angular JS.

I have some items that trigger an alert when clicked, it works fine for items that are not loaded via an HTTP request. However, the click event does not work for items loaded via AJAX.

Here is the HTML code: (the alert only works for the first two non-ajax items)

<ion-list>
    <div style="height:40px;border-bottom:1px solid #ccc" id="clickit">
          Item No Ajax call
    </div>
    <div style="height:40px;border-bottom:1px solid #ccc" id="clickit">
          Item No Ajax call
    </div>
    <div ng-repeat="item in items" style="height:40px;border-bottom:1px solid #ccc" id="clickit">
          Item Ajax Call: {{ item.username }}
    </div>

</ion-list>
<ion-infinite-scroll ng-if="!noMoreItemsAvailable" on-infinite="loadMore()" distance="10%"></ion-infinite-scroll>

</ion-content>

Here is the JavaScript code:

angular.module('ionicApp', ['ionic']).controller('MyCtrl', function($scope,$http) {
    $("div#clickit").click(function() {
        alert('hey');
    });


    $scope.noMoreItemsAvailable = false;
    $scope.currentPage = 0;
    $scope.loadMore = function() {
        $http.get('http://mourjewels.com/www/stones2.php?page='+$scope.currentPage).success(function(items) { 
            $scope.currentPage += 1;
            $scope.items = $scope.items.concat(items.data);
            console.log(items.count);
            $loopcount =  Math.ceil(items.count/10);
            console.log($loopcount);
            $scope.$broadcast('scroll.infiniteScrollComplete');
            if($scope.currentPage >= $loopcount){
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $scope.noMoreItemsAvailable = true;
            }
        });

      };

      $scope.items = [];
});

Answer №1

The reason for this behavior is that Angular runs your controller script before the dynamically loaded elements are added to the DOM.

However, with Angular, there is a different way to handle this. You can utilize Angular's ng-click directive.

In your controller,

$scope.doSomething = function () {
    // Performs an action
};

In your HTML,

<div ng-click="doSomething()"></div>

Directives in Angular, like ng-repeat and ng-click, are custom extensions to the native DOM. The ng- prefixed directives are part of Angular's core functionalities. During each update of the DOM by AngularJS, it identifies and executes the directives present. In your scenario, the ng-repeat and ng-click directives are executed. The ng-click directive specifically adds an onclick event handler to the DOM to trigger the specified function (doSomething) within the current scope. Therefore, it will function properly regardless of when or how the DOM elements are injected.

This is a simplified explanation, but I hope it clarifies the concept for you :)

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

The propagation of SVG events from embedded images via the <image> elements

I'm currently developing a diagramming tool using HTML, CSS, and Javascript with SVG for the drawing canvas. This tool consists of predefined "building blocks" that users can place on the canvas, rather than allowing free-hand drawing of shapes. Each ...

Here are the steps to divide an array of objects into separate objects based on their keys

The data I currently have is formatted like this: [{ "Consumer": [{ "Associated ID": "JSUDB2LXXX / BIC 7503 / US", "Parent Consumer": "7503" }], "Owner": [{ &qu ...

Replicate the action of highlighting a section of a website and copying it to the clipboard using JavaScript

I am currently in the process of transferring an outdated application to a new platform, but I'm facing difficulty understanding the changed JavaScript code. My goal is to find a parent HTML element named "output" and then select all its child elemen ...

JavaScript comparing elements within an array

I need help extracting all the names from an array with URLs containing '/blekinge' and presenting them in a list. Here's what I have so far: const allLocations = locations.map((location) => <li>{location.url}</li> ) I&a ...

What is the best way to ensure that my website functions properly on Safari mobile?

I successfully created a website that functions well on my computer across all modern browsers. However, a user reported that it is not working on Safari mobile. Upon testing the website on Safari for Windows, it appeared to display correctly. After view ...

Circular dial progress bar with dynamic data loading

I am currently experimenting with Knob and AJAX. The issue I'm facing is that although the number inside changes in real time, the progress bar remains static. You can view the project here: www.skincannon.com The code snippet is as follows: HTML: ...

Sails JS - Flash message display issue on Heroku in production environment, works smoothly in development mode

I'm experiencing an issue with the flash message on my local machine during development, as it works fine there but not when I deploy the app on Heroku. I've been searching for a solution without any luck so far. api/policies/flash.js module.ex ...

What reasons could be preventing the state from updating correctly in Vuex?

Currently, I am working on a project where I am utilizing vuex along with axios to retrieve data from the backend. The issue arises when I try to access the state - even though the updated state is displayed successfully when I console-log it, there seems ...

The jQuery code fails to run when a button is clicked inside an update panel

Can anyone assist me with an issue I am encountering? I have a button inside an update panel and I am using jQuery scripting to style the elements on this particular page. Initially, when the page loads, everything looks fine as the CSS styles are applie ...

Having trouble with Angular2's Maximum Call Stack Exceeded error when trying to display images?

I am facing an issue in my Angular2 application where I am trying to display an image in Uint8Array format. The problem arises when the image size exceeds ~300Kb, resulting in a 'Maximum Call Stack Exceeded' error. Currently, I have been able to ...

Utilizing jQuery and PHP to transfer a parameter

I am looking for a way to send the file value to catch.php using jQuery. Is there a method to pass the file value to catch.php so that var_dump($_FILES) will display something? ------index.php------------ <p>Name: <input type="text" name="name" ...

Activate the CSS on a click event using the onClick method

I am trying to implement a transition that triggers when clicking on a specific div element. Currently, the transition only occurs with the active css class. How can I achieve this effect by simply clicking on the div itself? I am using reactjs and believe ...

Tips for creating a plug-in plugin and applying the necessary parameters

(function( $ ){ var functions = { init : function( options ) { var settings = $.extend({ //Declaring default settings that can be overridden in the plugin call code: 7, listHe ...

After deploying to Firebase, animations suddenly cease to function

After running npm run-script build and deploying my React app to Firebase hosting with firebase deploy, I encountered an issue where my animations stopped working. I'm puzzled as to why this is happening, especially since I've included keyframes ...

Achieving proper stacking of a table with other div elements

I've come across some similar inquiries, but none seem to fully address the specific issue at hand. If there's an existing thread on this that I overlooked, I apologize in advance. So, here's a multi-part problem: my solution for the first ...

The anchor tag is not being used in the function call in an Angular application

Having trouble with calling the logout function inside the login controller. The setup involves a simple login and logout system using ui-router. After successfully logging in and navigating to another page, I encountered issues with calling the logout fu ...

What is the process for setting up a subrouter using React Router v6?

This is the current React Router setup I am using: const router = createBrowserRouter([ { path: "/", element: ( <Page activeNav="home" > <Home /> </Page> ) }, { ...

Using Local IIS to host both Angular JS and Web API 2 on the same port

Is there a way to host my client and server on the same port? I have an Angular JS front end and Web API 2 service that I want to run on the same web server. I currently have IIS set up on my local machine, but I'm unsure of how to go about hosting b ...

Testing for connected components with a specific property (React/Redux)

Having a React component with Redux @connect decorator, a situation arises like this: import React, { Component } from 'react' import { connect } from 'react-redux' @connect(mapStateToProps, { onPress: () => {...code}) // The ...

Using jQuery's .remove() function removes all of the children from the container, rather than just one at

For my latest project, I am focused on creating a seamless full-page transition using AJAX calls. The challenge I'm facing is removing content from the DOM when loading in a new page. Despite adding a unique class or ID to the element, the .remove() f ...