Understanding the behaviour of injecting attributes in directive scopes

Can anyone provide some insight on why my JavaScript key code isn't working as expected in the second directive of my example below? It seems that injecting scope attributes is causing the function passed into the directive not to be evaluated properly. The first directive, however, works fine without any scope injection.

Could this be intended behavior or am I making a mistake somewhere?

angular.module('taskLister', []);

angular.module('taskLister')
  .controller('ListController', ListController);
ListController.$inject = ['$log'];

angular.module('taskLister')
  .directive('keyPresser', keyPresser);
keyPresser.$inject = ['$log'];

angular.module('taskLister')
  .directive('keyPresserNotWorking', keyPresserNotWorking);
keyPresserNotWorking.$inject = ['$log'];

function ListController($log) {

  var vm = this;
  vm.editingListTitle = false;
  vm.editListTitle = editListTitle;
  vm.finishedEditListTitle = finishedEditListTitle;

  function editListTitle() {
    vm.editingListTitle = true;
    $log.info('editing');
  }

  function finishedEditListTitle() {
    vm.editingListTitle = false;
    $log.info('finished editing');
  }

}

//********
//Working
//********
function keyPresser($log) {

  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.bind('keydown keypress', function(event) {

        if (event.which === 13) {
          scope.$apply(function() {
            scope.$eval(attrs.keyPresser);
          });
          event.preventDefault();
        }
      });
    }
  };

}

//********
//Not Working
//********
function keyPresserNotWorking($log) {

  return {
    restrict: 'A',
    scope: {
      key: '@key'
    },
    link: function(scope, element, attrs) {
      element.bind('keydown keypress', function(event) {

        scope.key = Number(scope.key);

        if (event.which === scope.key) {
          scope.$apply(function() {
            scope.$eval(attrs.keyPresserNotWorking);
          });
          event.preventDefault();
        }
      });
    }
  };

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>

<div ng-app="taskLister">


  <div ng-controller="ListController as vm">

    has the user pressed enter? - {{vm.editingListTitle}}
    <br/>

    <input type="text" key-presser="vm.editListTitle()" placeholder="Press Enter">
    <br/>

    <input type="text" key-presser-not-working="vm.editListTitle()" key="13" placeholder="Press Enter but it doesnt work">
    <br/>

    <button ng-click="vm.finishedEditListTitle()" type="button">Reset</button>
    <br/>

  </div>


</div>

Appreciate any help provided! :)

Answer №1

There is an issue with your code because you have enclosed it within

scope: { key: '@key' },

You need to include your key-presser-not-working attribute in your scope like this:

scope: {
    key: '@key',
    keyPresserNotWorking: '&'
 },

Then, you can call it using scope.keyPresserNotWorking() in your link method.

Here is the corrected code:

function keyPresserNotWorking($log) {

  return {
    restrict: 'A',
    scope: {
      key: '@key',
      keyPresserNotWorking: '&'
    },
    link: function(scope, element, attrs) {
      element.bind('keydown keypress', function(event) {

        scope.key = Number(scope.key);

        if (event.which === scope.key) {
          scope.$apply(function() {
            scope.keyPresserNotWorking();
          });
          event.preventDefault();
        }
      });
    }
  };

}

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

perform a JSON request in a RESTful manner

Can you explain the concept of making a RESTful JSON request? In the given scenario, when Backbone attempts to read or save a model to the server, it calls upon the function known as Backbone.sync. This function, by default, utilizes (jQuery/Zepto).ajax t ...

What could be causing the "Cannot POST /api/" error to occur when attempting to submit a form?

Having issues with my basic website and struggling to find a solution. As a complete beginner in this field, I am stuck and need some guidance. Accessing http://localhost:3000/class/create works perfectly fine when running the server. However, trying to a ...

Combining two arrays into one array using a foreach loop

let colors = ["red", "blue"]; let sizes = ["s", "m", "L"]; //Desired output: let finalResult = [ { id: 0-0, val: 'red/s' }, { id: 0-1, val: &a ...

Set the height of the div to match the length of the downward swipe

I am working on gradually revealing a div as the user swipes down on the body element. Currently, I am using jQuery along with hammer.js to detect the swipe gesture, but I need assistance in determining the distance of the swipe and adjusting the height o ...

"Create a function that allows for the dynamic addition of elements to a

I want to dynamically add more li elements, similar to the first one, by simply clicking a button. Unfortunately, the example provided on jsfiddle is not functioning as intended. document.onload = init; function init(){ document.getElementById('a ...

MUI Gradient Tracked Button

Take a look at this Codepen example I created. It showcases a hover effect where the gradient follows the mouse cursor. In order to achieve this effect, I have defined two CSS variables - --x and --y, to keep track of the mouse position on the button. The ...

The toArray function in MongoDB does not support the use of Array push

I'm attempting to loop through all documents within collections, store them in a global variable, but it seems like the push() function is not working and returning an empty array [] inside of toArray(). Any ideas? const mongo = require('mongodb ...

Is JavaScript overwriting the existing value?

I am completely new to JavaScript and I am struggling with a seemingly simple issue. I have an array of usernames that I am iterating over. My goal is to map these usernames to click event methods, although I am aware that this may not be the most efficien ...

The deployment of my Node application on Heroku is causing an error message: node-waf is not

I've been trying to deploy my Node.js application on Heroku by linking it to my Github repository and deploying the master branch. Despite experimenting with various methods, I keep encountering the same error every time. You can view the detailed b ...

What is the reason behind the lack of preservation of object state when using Promises?

Here is a code snippet to consider: class ClientWrapper { private client: Client; constructor() { this.client = new Client(); } async connect() : Promise<void> { return this.client.connect(); } async isConne ...

Managing multiple checkboxes in a Vue component

I have a checkbox component in Vue: <template> <div class="checkbox"> <input class="checkbox-input" name="input" type="checkbox" v-model="checkbox"> </div> </templ ...

A guide on integrating the MUI Timepicker with the newest 6 version using Formik

I am currently experimenting with the MUI React Timepicker component and facing an issue during integration with Formik for validation. The problem lies in the inability to bind values properly in the initialValues of the form. const [initialValues, setI ...

AngularJs - utilizing two-way binding within an ng-repeat using a view model concept

I am working on a project where I have multiple checkboxes displayed using ng-repeat in the following manner: <tr data-ng-repeat="item in blogCategory.items track by $index"> .... <td> <label class="toggle"> <input ...

Incapable of modifying the text within a div container

I am currently working on a script that translates a Russian forum word by word using TreeWalker. However, there is a specific type of div element that I have been unable to change the text for. That leads to my question: How can I go about changing it? Un ...

acquire an array in javascript from an object

Currently, I am in the process of building a google authentication chat website and everything has been going quite smoothly. In fact, most of the work is already complete, except for one final task - retrieving messages from a JSON database. While I am ab ...

Tips for arranging accordion buttons side by side so they all expand into a single element

I'm currently working on a unique accordion design where multiple buttons expand into individual areas below when clicked. The standard accordion layout isn't quite what I'm aiming for. I envision the buttons all in a row, and when clicked, ...

Using JavaScript to pass a value from an input field to a href attribute

I am currently working on a scenario where, upon clicking on an input field, the value is passed to a URL and the corresponding radio button is checked. This way, I can share the URL with someone else. Unfortunately, I have hit a roadblock in my progress: ...

I want to display events from my database table on their corresponding dates using JavaScript and jQuery. How can I achieve this?

Using the FullCalendar plugin, I attempted to achieve a specific functionality, but unfortunately fell short of my goal. Below is the snippet of my scripting code: $('#calendar').fullCalendar({ //theme: true, header: { ...

Building Unique Staircases with Three.js Geometry

I have been working on creating a custom three.js geometry for round staircases, but I seem to have made some errors with the vertices and indexes of the steps. Below is an example staircase that utilizes my custom geometry: https://i.sstatic.net/uQXvP.j ...

Showing XML content with JavaScript

Trying to parse a simple XML list using JavaScript, but having trouble formatting it the way I need. <TOURS> <MONTH> <TOUR> <NUMBER>1</NUMBER> <VENUE>City Name - Venue Name</VENUE> < ...