The $scope variable fails to reflect updates in the view following a broadcast event triggered by a

I have been troubleshooting a similar issue and I can't seem to figure out why the update is not reflecting in the view. While I am able to see the scope variable updating in the catch events logs, the changes are not being displayed in the view. For example, it shows "test" initially but does not change when $scope.keyPressed is updated.

the directive

app.directive('keypressEvents', [
  '$document',
  '$rootScope',
  function($document, $rootScope) {
    return {
      restrict: 'A',
      link: function() {
        $document.bind('keypress', function(e) {
          console.log('Got keypress:', e.which);
      
    		$rootScope.$broadcast('keypress', e);
          $rootScope.$broadcast('keypress:' + e.which, e);
        });
      }
    };
  }
]);

the controller

$scope.keyPressed = 'test';
$scope.$on('keypress:13', function(onEvent, keypressEvent) {
          $scope.keyPressed = 'Enter';
          console.log($scope.keyPressed);
        });
        
        $scope.$on('keypress', function(onEvent, keypressEvent) {
          if (keypressEvent.which === 120) {
            $scope.keyPressed = 'x';
          } else {
            console.log('else' ,keypressEvent);
            $scope.keyPressed = 'Keycode: ' + keypressEvent.which;
          }
        });

the view

<div data-keypress-events>
    {{keyPressed}}
</div>

The controller for the view is determined by the route provider when it loads the partial.

.when('/feed/:url', {
            templateUrl: '/templates/eventWall-feed',
            controller: 'eventWallFeedController'
        })

Answer №1

$on and $broadcast do not automatically trigger $apply, so you must use an $apply wrapper for $scope.keyPressed like this:

$scope.$apply(function() {
  $scope.keyPressed = 'x';
});

Answer №2

One suggestion is to include a $scope.$apply() at the conclusion of the keypress event.

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

Requesting data from a server using jQuery's AJAX functionality

Currently, I am utilizing the following piece of code for an ajax call: $('#filter').submit(function(){ var filter = $('#filter'); $.ajax({ url:filter.attr('action'), data:filter.serialize(), // form ...

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

What is the process for passing external JSON data to a task from a file that was generated in a previous task?

Currently facing an issue with the following setup in my Gruntfile: grunt.initConfig({ shell: { // stub task; do not really generate anything, just copy to test copyJSON: { command: 'mkdir .tmp && cp stub.json .tmp/javascript ...

Implementing a JQuery click method within a class structure

I'm having trouble getting the functionality of the .click function to work on my page unless I paste it into the browser console. In my class, this is what I have: var myClass = function(){ var toggleChecked = function(){ $('#myCheck ...

What strategies can be used to ensure that the page layout adjusts seamlessly to even the smallest shifts in window size?

Of course, I am familiar with media queries and how they allow us to set specific min-width and max-width ranges for CSS changes. However, when I look at the website styledotme.com, I notice that the block/div beneath the navigation bar gradually shrinks ...

Variations in key-codes between Android Nexus and Samsung mobile devices

As I work on developing a "Pin Code Entry" functionality for an Ionic app, I encounter challenges with different key-codes on various Android devices. The goal is to create a login feature where users input digits into 5 fields using a Numeric keyboard. Th ...

Establish a timeout for the Material UI drawer to close automatically after being opened

I am looking for a way to automatically close the drawer after a specific duration, but it seems that material UI drawer does not have the necessary props for this. Is there a workaround using transitionDuration or perhaps adding a setTimeout in my functio ...

Tips for positioning a React component above another component

I am currently facing a challenge while working on a table with an expand more option to display additional details for each specific row. I have implemented a slider to facilitate the expansion of the table. Presently, my ExpandToggle component is embedde ...

What is the limitation in transmitting data as a JavaScript object rather than a JSON object?

As a newcomer to expressjs, I recently developed an application using it. Interestingly, when I send data in JSON format through POSTMAN, the application successfully returns the data. However, when I try to send data as a JavaScript object in the request ...

The functionality of the jQuery .click method appears to be malfunctioning within the Bootstrap

It seems like my JQuery.click event is not functioning as expected when paired with the corresponding button. Any ideas on what might be causing this issue? Here's the HTML CODE snippet: <button id="jan7" type="button" class="btn btn-dark btn-sm"& ...

What steps can I take to prevent already selected options from being chosen in a Vue.js HTML form?

Among my json data, I have a list of all inventories: { "status": true, "data": [ { "inv_id": 1, "name": "Arts" }, { "inv_id": 2, "name": "web" }, { "inv_id": 3, "name": "mobileapp" }, { "inv_id": 4, "name": "ws" }, { "inv_id": 5, ...

Tips for including a JWT token as a query parameter in NEXT js?

const UserJwt = (props) => { const { jwt } = props; const [jwtToken, setJwtToken] = useState(null); useEffect(() => { if (jwt) { setAuthToken(jwt); setJwtToken(jwt); } }, [jwt]); return <MobilePurchaseScreen {...pro ...

What is the best way to retrieve an element from a JSON scope based on the value of another JSON scope in AngularJS?

I am dealing with two simple JSON scope variables. My goal is to display a specific object's value from the first JSON based on another object's value in the second JSON, For example: {{json1.json2.id}} The issue I'm facing is that Angula ...

Pause the audio using jQuery when the slide changes

I have a Drupal website with a slider that includes an audio player on each slide. I need the audio to stop whenever the slide changes. The slider plugin I'm using is owlCarousel. Here is my current code: $("#owl-demo").owlCarousel({ afterAction: ...

The list marquee in HTML, JS, and CSS is not being properly rendered on

I recently made changes to a code that showcases a marquee scrolling a basic HTML list. Check it out here: I am facing 3 issues that I am struggling to resolve: JS: I want the marquee to continuously show text re-entering from the right just after it ...

Deciphering HTML elements using JSON within the Angular framework

Upon receiving JSON data from my server, the reviews array is typically filled with numerous reviews. However, for demonstration purposes, I am presenting only one review here. { "reviews": [ "<br>We have found 20 reviews on external web ...

Reveal concealed fields following the selection of a specific option

I'm looking to create a bookmarklet that will automatically fill in values when clicked. Currently, I can select values using: document.getElementById('component').value="IAE-Data Agent"; document.getElementById('component').onch ...

Unable to assign a local variable in Jquery .ajax() function to a global variable

Check out this example of a jQuery AJAX code: $(document).ready(function() { var custom_array = new Array(); $.ajax({ url: 'data.json', type: 'get', dataType: 'json', success: function(response) { $ ...

Strategies for passing a JavaScript variable to a JSP function

I'm dealing with a JavaScript code that has a value stored in its variable that I need to pass to my JSP function. However, I'm facing trouble passing it along. Take a look at the following code snippets: Javascript: $('button').on(& ...

Unveiling the Magic: Displaying Quill's raw HTML in Vue.js

Within my Vue.js app, I am utilizing the Quill editor to generate raw HTML content that is saved directly to the database without any cleaning. When fetching this content from the backend, the text and styling are displayed correctly (colors, bolding, etc. ...