AngularJS directive not registering event after model update

Within my angularjs application, I have implemented an element directive that is equipped with an event listener. This listener is designed to respond to a broadcast event from the controller.

app.directive('listItem', function(){
  return {
    link: function(scope, element){
        scope.$on('controllerEvent', function(e,attr) {
            console.log('event fired!')
        });
    },
    templateUrl:'views/fragments/list.html'
  }
}]);

The directive in question is used multiple times within my view through the ng-repeat directive and an array.

Upon loading the view, all listeners are triggered appropriately when the event occurs. However, when a new item is added to the array leading to another instance of the directive being rendered, its corresponding listener does not execute. Is there a way to manually ensure that it binds?

Answer ā„–1

In order to trigger the event listener, you must fire a shot

$rootScope.$broadcast('customEvent', {});

This should happen every time there is a change

Answer ā„–2

Through much experimentation, I finally discovered a solution.

By binding it to the local scope of the directive, there seemed to be a loss of reference when additional data was added. To resolve this issue, I made a simple adjustment and changed the binding to $rootScope (which required injecting it into the directive);

app.directive('listItem', ['$rootScope', function($rootScope){
    return {
        link: function(scope, element){
            $rootScope.$on('controllerEvent', function(e,attr) {
                console.log('event fired!')
            });
        },
        templateUrl:'views/fragments/list.html'
    }
}]);

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

Guide to incorporating Bootstrap into Karma-Jasmine for automated testing in AngularJS

My directive is calling a method from bootstrap.min.js, but when I try to test it by writing a test file, I get an error saying that the function I used is not defined. I believe the error is due to Bootstrap not being included in the test environment. I ...

Issue with Sequential Drop Down List Functionality in ASP.Net MVC View Page

I am currently in the process of migrating code from one project to another. Although the code works fine in the original project, it is not functioning properly in the new one. Iā€™m uncertain if something was overlooked on my end. Within this code, ther ...

React component fails to display content following execution of Jquery Ajax request

Utilizing a basic jQuery ajax function to retrieve inline HTML code from an API $.ajax({ url: url, headers: { 'Accept': 'application/javascript' }, dataType: 'html', beforeSend: function(){ $('.load-mor ...

Exploring the power of NodeJS modules through exports referencing

Encountering difficulties referencing dynamic variables related to mongoose models based on user session location value. Two scripts are involved in this process. The first script is called location.js & reporting.js In the location.js script: module.ex ...

Choosing between exclusive choices across multiple selection elements in Vue 3

In my Vue component, there are 5 distinct values stored in the options variable. I want users to select only one value from each of the 5 select options I provide. This means that once a user selects a value in one input select component, that same value c ...

Encountering issues with Office.context.document.getFileAsync function

I am experiencing a strange issue where, on the third attempt to extract a word document as a compressed file for processing in my MS Word Task Pane MVC app, it crashes. Here is the snippet of code: Office.context.document.getFileAsync(Office.FileType.Co ...

How to set URL query parameters in Angular ui-router without altering the state

What is the best way to update the address bar URL with a changing query parameter using AngularJS' ui-router while preserving state after page refresh? I have been utilizing $state.transitionTo('search', {q: 'updated search term' ...

window.onresize = function() { // code here

Here's an example of code I've been working on: $(document).ready(function (e) { adjustSize(); $(window).resize(adjustSize); function adjustSize() { var windowWidth = parseInt($(window).width()); if (windowWidth > ...

Having trouble locating the name WebGLObject in my TypeScript code

Every time I try to run ng serve command An error pops up on my screen saying: "WebGLObject cannot be found." ...

A guide to utilizing ng-model for binding data in table rows for inline editing

I am facing an issue with the getTemplate function in my AngularJS application. I have an object with 3 values empID, empName, empEmail and here is my code: var app = angular.module('myApp' , []); app.controller('myCtrl' , function($ ...

Unable to add items to the collection in NPM with Meteor 1.3

I have encountered an issue with the imap-simple NPM package while trying to perform an insert operation. Despite following the suggestions on , I am still unable to get the insert function to work properly! Even after simplifying the code and eliminatin ...

Avoiding scrolling when a button (enveloped in <Link> from react-scroll) is pressed in React

Currently, I am implementing the smooth scroll effect on a component using react-scroll. However, adding a button inside the component to create a favorite list has caused an issue where the smooth scroll effect is triggered upon clicking the button. Is ...

Is it possible to utilize Angular translate to support multiple languages for individual components or modules?

Utilizing ngx-translate to switch the language of my application has proven to be quite challenging. My application consists of different languages specifically for testing purposes and is divided into separate modules with lazy loading functionality. As ...

Having trouble with your Bootstrap 4 Dropdown Menu?

I attempted to implement the dropdown menu example from Bootstrap 4, but unfortunately it does not seem to be working as expected. The dropdown menu does not appear when clicked. <li class="nav-item dropdown"> <a class="nav-link dropdown-to ...

Session is required for req.flash() function in node.js to work properly

I recently started working with Node.js and I'm encountering an issue with sessions. I developed a simple application and tried to run it locally, but ran into some errors. Below are the details of my code along with the error messages: BAPS.js (app. ...

Create a selection menu in an HTML dropdown list using unique values from a JSON object that is separated by commas

I'm working with a JSON object that contains multiple key value pairs, one of which is the Languages key. This Languages key holds comma-separated values such as "English, Hindi, French," and so on. My goal is to extract distinct values from the Lang ...

What is the best way to conceal a row when a particular field is devoid of content?

Is it possible to hide an entire table row if a field is empty? For example: https://i.sstatic.net/tMW7L.png If a certain field is empty, I want the entire row to be hidden, either using JavaScript or jQuery. I have tried some methods but none of them fu ...

`Is there a way to manipulate the timer in JavaScript?`

My current project involves creating a timer in minutes and seconds. The user inputs the desired time in minutes into a textbox named "textbox2". However, when I attempt to retrieve the value of this input using `getElementById.value`, it returns a NULL er ...

I am unable to reach my pages through their URL directly, I can only access them through links within Next.js

My next JS application runs smoothly during development, but encounters an issue when published online. I can only access the pages through links on the home page that direct to those specific pages. For instance, trying to navigate directly to www.examp ...

Struggling with TypeScript and JsObservable? Let us assist you!

Having previous experience with JSRender, JSViews, and JSObservables, I recently embarked on a new project using TypeScript. Unfortunately, I am struggling to understand how to properly utilize TypeScript in my project, especially when it comes to referenc ...