Instruction to pay attention to the event

After noticing that I've added similar event listening code to many of my controllers, I began to think about how to streamline it. The code looks something like this:

  document.addEventListener("resume", function(e){
    $scope.doSomething();
  }, false);

It became apparent that having the same code scattered throughout isn't ideal, especially when the only variation is the $scope.doSomething().

My idea was to create a directive so that I could use something like this:

<div on-resume="doSomething()">
</div>

I attempted to implement this (unsuccessfully):

.directive('onResume', function(){ 
   return {
      restrict: 'A',
      link: function(scope, elem, attr, ctrl) {
         elem.bind('resume', function(e) {
            fnName = attributes["onResume"];
            scope.$apply(function(){ 
              scope[fnName]();
            });
         });
      }
   };
});

Any suggestions or insights?

Answer №1

By implementing an isolate scope, you have the ability to pass a function with one-way data binding. If you have a function called doSomething defined on your parent scope, the following code snippet will allow it to work seamlessly with the provided HTML.

.directive('onResume', function() {
  return {
    restrict: 'A',
    scope: {
      onResume: '&'
    },
    link: function(scope, elem, attr, ctrl) {
      elem.bind('resume', function(e) {
        scope.$apply(function() {
          scope.onResume();
        });
      });
    }
  };
});

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

Failure to receive a server response during the AJAX communication

I am facing an issue with my code that is making 3 requests to a server. The code successfully sends the request, but fails when receiving the response. I need help in skipping the first response and only getting the third one. phone.open("POST", '/& ...

Is it possible to write a text file in UTF-16 using Javascript?

I need to create a UTF-16 text file from a string. For instance: var s = "aosjdfkzlzkdoaslckjznx"; var file = "data:text/plain;base64," + btoa(s); The above code generates a UTF-8 encoding text file. How can I modify it to produce a UTF-16 text file usin ...

Issue with restricting table size in AngularJS not resolving

I need assistance with limiting the size of a table to 5. Here is my current code snippet: <tr ng-repeat="(key,value) in cla|limitTo:5"> <td class="mdl-data-table__cell--non-numeric">{{ key}}</td> <td class="mdl-data-table_ ...

Achieving 10 touchdowns within a set of 5 plays during a football game

Receiving a page from an external site where I have no control. The table structure is as follows: <table><tbody> <!-- headers --> <tr><td></td> <td></td> <td></td> <td>< ...

Navigating with Anchors, Styling and jQuery

Firstly: Apologies in advance for any language errors as English is not my native tongue. :) The Scenario Here's the deal: I'm attempting to create a single button that, when clicked by the user, automatically scrolls down to the next DIV. Each ...

How can I display a timer icon in front of text on a Material-UI CardHeader subtitle?

I have a question regarding displaying time in my posts. Currently, I am showing the time as 'a few seconds ago', '2mins ago', 'an hour ago', etc. However, I would like to include a clock icon before this string. Although I a ...

angular pagination directive malfunctioning

I have developed a custom directive for pagination that is compatible with grids throughout my website. On this particular page, there is a search feature that retrieves new data, and I am looking to update the pagination within my directive with this new ...

A guide on implementing AJAX redirection in MVC

I currently have a button that, when clicked, takes input values and redirects to another page in JavaScript using the following code window.location = "Action Param1=value1&Param2=Value2". However, I am looking to avoid using query strings for this me ...

Optimal techniques to ensure model validation through the utilization of a REST API and a cutting-edge javascript front-end like Angular

As I delve into developing more responsive front-end web applications, a question arises regarding model validation. Let's set the stage: our server has a REST API that handles various operations such as inserting, updating, and retrieving data. It ca ...

Learn how to incorporate a consistent header and footer across multiple pages on a website with Node.js, ExpressJS, and either hbs or ejs templates

Creating a common header (navbar) and footer page to be included in multiple/several pages of a website. I want to create a dynamic website using Node.js and Express.js. The code for the navbar and footer will be placed in a common file named header.html ...

Dissipating visuals / Effortless website navigation

Do you have experience working with HTML or are you looking for specific code examples? I've noticed some websites with sliders that feature clickable images fading in as soon as the page loads. I tried searching for information on how to achieve thi ...

Ways to change object to string in javascript

My object has the following structure: Object {Dry Aged Ribeye(medium): "1" , Dry Aged Ribeye(rare): "1" , Dry Aged Ribeye(well): "1" , favorite_tables: "{"dc76e9f0c0006e8f919e0c515c66dbba3982f785":[]}" } I am trying to insert this into My ...

a single button with dual functionalities

I am new to the development field and have a question about jQuery. I want a single button to perform two different actions. For example, let's say we have a button labeled Pause/Resume. When I click on the button, it should first display "Pause", and ...

Ways to conceal a grid item in Material UI framework

My goal is to hide a specific grid item for a product and smoothly slide the others in its place. Currently, I am using the display:none property but it hides the item instantly. I have already filtered the products and now I want to animate the hiding of ...

Exploring the benefits of utilizing EmberJS within the metalsmith.IO platform

Trying to integrate EmberJS into a codesmith.IO project previously built with Angular 1. Feeling like I'm overlooking something simple when it comes to the implementation process. Since I typically use Ember CLI for new app templates, I'm unsure ...

Has the rotation of the model been altered?

Is there a way to detect if the rotation of a model has changed? I've attempted: var oldRotate = this._target.quaternion; console.log('works returns vector3 quaternion: ', oldRotate); var newRotate = oldRotate; if (oldRotate != ...

Using both withNextIntl and withPlaiceholder simultaneously in a NextJS project causes compatibility issues

I recently upgraded to NextJS 14 and encountered an issue when deploying my project on Vercel. The next.config.mjs file in which I wrapped my nextConfig in two plugins seemed to prevent the build from completing successfully. As a workaround, I decided t ...

Dividing a string into an array and displaying it in a table using Laravel

Retrieving a string from the database and using the explode function to split the values. Below is the code snippet: $data = DoctorRegistration::select('products') ->where('doctorid','=',$doctorid) ->get(); ...

Displaying Bootstrap alert after a successful jQuery AJAX call

I have been attempting to display an alert on a form once the submission action is completed. Here is my JavaScript function: function submitForm(){ // Initialize Variables With Form Content var nomeCompleto = $("#nomeCompleto").val(); v ...