directive encapsulating basic functionality

I'm currently working on creating a directive that can sort any type of data at any point within my application. Let's take a look at the code snippet below (which is based on actual code, but simplified for clarity):

angular.module('test', []);
angular.module('test').controller('wrapperController',['$scope', function(scope){
  scope.data = {}
  scope.data.rows = [{name: 'foo'}, {name: 'bar'}, {name: 'bazz'}]
  scope.data.columns = [{name: 'Name', sortBy: 'name'}]
}]);
angular.module('test').directive('grid', [function(){
  return {
    restrict: 'A',
    templateUrl: 'grid.html',
    scope: {
      grid: '='
    }
  }
}]);
angular.module('test').directive('sortable', [function(){
  return {
    restrict: 'A',
    scope: {
      sortableCollection: '=',
      sortableKey: '&'
    },
    compile: function(el, at, transclude){
      if(at['ng-click']){
        el.attr('ng-click', el.attr('ng-click')+';sortFunction()')
      }else{
        el.attr('ng-click', 'sortFunction();')
      }
      return(function(scope, element, attrs){
        scope.sortableKey = scope.sortableKey();
        scope.sortFunction = function(){
          alert(" I AM IN UR FUCNTION SORTING UR D00dZ!!1");
        }
      });
    }
  }
}]);

Here's the HTML:

<body ng-app='test'>
    <div ng-controller='wrapperController'>
      <div grid='data'></grid>
    </div>
  </body>

and (in grid.html):

    <div>
  <table>
    <thead>
      <tr>
        <td ng-repeat='column in grid.columns'>
            <div sortable sortable-collection='grid' sortable-key='column.sortBy'>{{column.name}}</div>
        </td>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat='row in grid.rows'>
        <td ng-repeat='cell in grid.columns'>
          {{row.name}}
        </td>
      </tr>
    </tbody>
  </table>
</div>

Upon inspecting the HTML, it appears that the ng-click attribute is being set correctly. However, despite this, the function does not execute when the header is clicked. What could be causing this issue? Is there a way to achieve the desired behavior?

plunr: http://plnkr.co/edit/aXjMqhZxI7ME8wQJOLpA?p=preview

Answer №1

Merely including an attribute does not automatically trigger the execution of a directive in Angular. Upon starting the application, Angular scans the DOM for directives and then calls their compile functions. Therefore, attempting to add ng-click within that function is ineffective.

It is illogical to insert ng-click within a directive. Instead, one should aim to incorporate an event listener for the click event.

link: (function(scope, element, attrs){
    scope.sortableKey = scope.sortableKey();
    element.on('click',  function(){
      alert("I AM IN UR FUCNTION SORTING UR D00dZ!!1");
       // Ensure to call $scope.apply(); after making changes to the model
    });

Answer №2

To implement a grid directive, you can create a control object on its scope:

link: function(scope, element, attrs) {
  scope.sorter = {};
}

Then, pass this control object to the sortable directive like this:

<div sortable sort-control='sorter'...></div>

The sortable directive will then assign the sorting function to the control object:

scope: {
  ....
  sortControl: '='
},
link: function(scope, element, attr) {
  if (scope.sortControl) {
    scope.sortControl = {
      sortFunction: function() {
        alert(" I AM IN UR FUCNTION SORTING UR D00dZ!!1");
      }
    };
  } 
}

Finally, in the grid template, you can access the sorting function by calling it as a property of the control object:

<div sortable ng-click='sorter.sortFunction()' sort-control='sorter'...></div>

For a demonstration of this implementation, check out the following link: http://plnkr.co/edit/iYkVbh2wGfCWBWA0SX3M?p=preview

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

Update settings when starting with chromedriver

I am currently using webdriver (), standalone selenium, and mocha for writing my test cases. These test cases are specifically designed for Chrome, so I rely on chromedriver for execution. However, when launching the browser, I need to ensure that the "to ...

Every time I try to launch NPM start, an error pops up on my screen

Whenever I try to execute the command: npm start An error message pops up saying: npm ERR! missing script: start This is what my package.json file looks like: { "name": "react-app", "version": "0.1.0", "private": true, "dependencies": { " ...

Navigating through paginated data can be made easier by using Backbone.PageableCollection in conjunction with a personalized

I have developed an application that interacts with a database known as LeanCloud. Currently, I have configured a page to display all the users stored in the database. However, LeanCloud has a limitation where only 100 pieces of data can be retrieved per r ...

Pressing the enter key does not submit the Vue.js form

When attempting to submit the form by pressing "enter" on the keyboard, it only works when I click the "submit" button. I made sure to add @submit to the form event to ensure it triggers, but upon checking a log, I found that it only triggers when clicking ...

Experience a unique custom layout using AppRouter in Next.js version 13, with the added

My goal is to encapsulate the _app.js file within a custom layout, similar to what I have done before. This way, I can include a Navbar at the top and wrap everything else within a container: //layout.js file import { Container } from 'react-bootstrap ...

Explore the inner workings and file contents of a package using the NPM registry API, by accessing a detailed JSON response

Can the NPM registry API be utilized to access an endpoint like https://registry.npmjs.org/jquery And examine the Tarbells structure and internal files without the need to download the package, in a JSON response similar to: { files: { js: registr ...

Looking to dynamically update a date variable based on user selection from a drop-down menu in PHP

I am currently working with a PHP file (index.php) which features a title bar displaying the date in the format (MM YYYY). The dates themselves are extracted from another PHP file named latest_update.php. Within the latest_update file, the dates are specif ...

What are the steps for loading JSON data into a select dropdown with the help of AJAX?

I am trying to create a dropdown list of schools using the select tag. Currently, I have hard coded values for the list, but I want to fetch the data from a RESTful service instead. Can someone please provide guidance on how to achieve this? <html& ...

dynamically load react icons

Is there a way to dynamically import an icon based on props received in a component and return a compatible icon? Here is the code in question: import { useEffect, useState } from 'react'; export default function Icon({ libraryName, iconName }) ...

Material-UI: The Mystery of Missing CSS Properties

Struggling to apply a CSS class to an element from Material-UI: bw:hover { -webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */ filter: grayscale(100%); } Tried using makeStyles: import { makeStyles } from '@material-ui/core/styles' ...

NodeJS Jest test failing due to a global variable being set for a different test already

I am currently working on a project in TypeScript using Node.js and Jest. I have a function that may or may not modify a global variable, which is a TypeScript Map. After one test modifies the global variable, it retains that value for subsequent tests. I ...

The jsonp typeahead feature is not populating the uib-typeahead form element

Trying to populate a uib-typeahead from the ui-bootstrap modules using a jsonp callback function in a factory method has been challenging. This is the factory function being used: autoCompleteCity: function(city){ return $http.jsonp("http://g ...

Integrating Angular into your current project

Currently working on a project that involves migrating from ASP.NET to Angular. While the transition is ongoing, we are interested in integrating Angular into our existing ASP.NET project. Has anyone had experience with this and can offer guidance on how ...

calculating the duration between successive PHP form submissions

I am trying to calculate the duration between when a user submits a PHP form and when they submit it again. The form reloads on the same page, essentially refreshing it. Additionally, the user may enter the same data again. I want the timer to start runnin ...

Using React Material UI icon within an auto complete feature

https://i.stack.imgur.com/W3CmF.png I am struggling to incorporate the target icon into the autoComplete component. After reviewing the documentation, I have been unable to find a solution. In TextInput, a similar outcome can be achieved by implementing ...

Incorporate JavaScript strings into HTML dynamically

I am facing some challenges with single quotes while trying to append HTML with a JavaScript string. So far, I have managed to successfully append the element: $("<a class='action-button' id='pl65197buy' value='buy now'&g ...

What is the best way to retrieve the identity or specifics of the item that was right-clicked within the context menu

My AngularJS populated table includes a link button. When I right-click on this button, I've created a specific context menu using jQuery that pops up. The issue arises when I try to retrieve the ID of the item I clicked on in the context menu (such a ...

Getting a "SyntaxError: Unexpected end of input" error while using jQuery ajax with valid JSON

The PHP response in JSON format shows: {"success":0,"message":"Error: No entityId passed!"} However, my JavaScript code throws an error "SyntaxError: Unexpected end of input". PHP: ... //check if an image id was passed for removal in the POST ...

View and Element UI combined for PDF previews prior to file uploading

I am currently utilizing Vue along with the element UI to enable file upload functionality, and I am also incorporating the pdfvuer node module. The uploaded files are ultimately being sent to Amazon S3. My goal is to allow users to preview the file befor ...

Tips for removing alert notifications from Pusher

I have integrated PUSHER into my website for notifications. The codes are successfully added and it is working fine. However, the issue arises when the alert is triggered as I am receiving messages that are not what I expected. The message received from t ...