AngularJS Compile directive allows you to specify functions that you want to run in

Can someone assist me in understanding how to call an external function from a built-in compile directive? Here is a code example: http://plnkr.co/edit/bPDaxn3xleR8SmnEIrEf?p=preview

This is the HTML:

<!DOCTYPE html>
<html ng-app="app">

    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <script src="script.js"></script>
    </head>

    <body ng-controller="myController as vm">

        <my-directive callback="vm.saveAction()" label="click me!"></my-directive>

    </body>

</html>

This is the JS:

app = angular.module('app', []);

app.controller('myController', function() {
    var vm = this;

    vm.saveAction = function() {
        alert("foo!"); 
    }
});

app.directive('myDirective', function() {
    var directive = {
        restrict: 'E',
        scope: {
            callback: '&'
        },
        compile: compile,
        link: link
    };

    return directive;

    function compile(element, attrs) {
        var template = '<button ng-click="action()">'+attrs.label+'</button>';

        element.replaceWith(template);
    }

    function link(scope, element) {
        scope.action = function() {
            // ...something useful to do...
            scope.callback();
        }
    }
});

I am aware that it can be done easily from the link function, but my requirement is to achieve it from the compile method. Can anyone provide guidance on this matter?

Appreciate your help!

Answer №1

To achieve this, utilize the template directive

app.directive('myCustomDirective', function() {
var customDirective = {
    restrict: 'E',
    scope: {
        callbackFunction: '&',
        title: '@'
    },
    template: '<button ng-click="performAction()">{{title}}</button>',
    linkFunction: linker
};

return customDirective;

function linker(scope, element, attrs) {
    console.log(scope.title);
    scope.performAction = function() {
        // ...do something useful...
        scope.callbackFunction();
    }
}

});

If you prefer using the compile method, consider utilizing either the pre or post method and compiling manually:

function compilation(element, attrs) {
   return {
      pre: function(scope, elem, attrs) {
          var dynamicTemplate = $compile('<button ng-click="performAction()">'+attrs.title+'</button>')(scope);

         element.replaceWith(dynamicTemplate);
      },
      post: function (scope, elem, attrs) {
         // Additional logic here if needed
      }
   }
}

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

Safari is unable to display the button text, while Chrome has no problem showing it

In Safari, the text of the button is not showing up properly. I am able to retrieve the text using jQuery in the console though. However, there seems to be an issue with recognizing the click event. <div class="btn-group btn-group-lg"> <button ...

Trouble arises when rendering nested components in React Router 4

My issue lies with implementing React Router 4 while utilizing "nested" routes. The problem arises when one of the top routes renders a component that matches the route, even though I do not want it to be rendered. Let me provide the relevant code snippets ...

The function angular.factory does not exist

Hey there! I am encountering an error in the title related to my factory. Any suggestions on how I can resolve this issue? (function (angular,namespace) { var marketplace = namespace.require('private.marketplace'); angular.factory(&apo ...

WebpackError: The global object "document" could not be found

I am encountering an issue with my website build using gatsby.js and bulma. While building the site, I receive the following error message: WebpackError: document is not defined The only instance where I use document is for the navbar-burger toggle code ...

Waiting for data to be passed from a parent component within a method

I have a situation where I need to make an API call in my layout and send the received data as an object to my component. The problem arises because the object is empty when the method is called inside the mounted() function. Therefore, I want to execute ...

Attempting to iterate through a Query each loop for the Raphael object

I'm currently facing a challenge with creating a jQuery .each() function to iterate through an array that I've constructed from a Raphael object. While I am able to achieve this using a traditional JavaScript for-loop: for (var i = 0; i < reg ...

My goal is to utilize React JS to generate a table by sending the values through props using an array of objects

I have experience building tables as part of various projects, but I am facing challenges creating a table based on the provided format for this specific project. My goal is to utilize the RecordTable Component, render the table component, pass the row com ...

Capture the 'value' of the button when clicked using ReactJS

I'm generating buttons dynamically using the map function to iterate through an array. Each button is created using React.createElement. ['NICK', 'NKJR', 'NKTNS'].map(function (brand) { return React.createElement(' ...

Capture a snapshot of a webpage that includes an embedded iframe

Currently, we have a nodeJS/angular 4 website that contains an iframe from a third party (powerBI Emebdded). Our goal is to develop a feature that allows the end user to capture a screenshot of the entire page, including the content within the iframe. We ...

Issue encountered during rootScope update

I've encountered an issue with my Angular service that updates the $rootScope. The actual updating process works as intended, but it triggers an error in the console that has me concerned. app.service("scroll", function($rootScope, $window) { this ...

Node.js tutorial: Fetching all pages of playlists from Spotify API

Currently, I am attempting to retrieve all of a user's playlists from the spotify API and display them in a selection list. The challenge lies in only being able to access 20 playlists at a time, which prompted me to create a while loop utilizing the ...

Show the MySQL query results in a pop-up alert box

I need assistance with querying a MySQL database for certain results using PHP and then displaying the result in an alert dialog box through JavaScript. I am able to connect to the database, query the data successfully, and display it on a PHP page. Howeve ...

Uploading images using the Drag and Drop feature in HTML

Hello, I'm having an issue with the drag and drop functionality. I want to expand the size of the input to cover the entire parent div, but for some reason, the input is appearing below the drag and drop div. Can anyone assist me with this? https://i. ...

Error encountered in TypeScript's Map class

When working with TypeScript, I keep encountering an error message that reads "cannot find name Map." var myMap = new Map(); var keyString = "a string", keyObj = {}, keyFunc = function () {}; // assigning values to keys myMap.set(keyString, "val ...

Unlock the App Store instead of iTunes Store using react-native-version-check

I am currently using react-native-version-check to trigger the opening of the app store or play store if an update is available. However, on iOS it redirects to the iTunes store instead of the desired AppStore location. Below is the code in question: ...

The Angular component is failing to display the template

After following a tutorial on UI-Router () I have implemented the following states in my Angular application: angular .module('appRoutes', ["ui.router"]) .config(['$stateProvider', '$urlRouterProvider', function($sta ...

using jQuery to eliminate an HTML element based on its attribute

How can I remove an element with the attribute cursor = "pointer"? I want to achieve this using JavaScript in HTML. Specifically, I am looking to remove the following item: <g cursor="pointer"></g>. It's unclear to me why this element has ...

In PHP, a boolean variable will not display on the webpage when echoed

I am facing an issue with my PHP code where certain variables are not being echoed properly in the generated JavaScript. The code is designed to check if specific values are assigned in the $_GET global array and assign default values if they are not prese ...

Force restart broken socket within Node.js program using Socket.IO programmatically

I have a simple one-to-one client and server Node.js based application. The Node.js is running on Linux (Intel Edison). I am attempting to automatically reboot the Linux server whenever the socket connection is broken. Is this achievable? Below is my unco ...

What is the best method for removing a class with JavaScript?

I have a situation where I need to remove the "inactive" class from a div when it is clicked. I have tried various solutions, but none seem to work. Below is an example of my HTML code with multiple divs: <ul class="job-tile"> <li><div ...