Update the ng-click event handler in Angular.js

I have a function defined in a directive called old(), currently the button executes this function when clicked. I want the old() function to be replaced with a new() function when the directive is loaded. The new function should receive (this.form) as a parameter, where "form" represents the name of my form. I attempted the following, but it did not work:

attrs.$set('ngClick', 'new(this.form)');

The new() function did not execute as expected. How can I achieve this? I specifically need to make these changes within a directive; while it might be possible in a controller, I am looking for a solution within a directive so that I could apply it to my actual project. Thank you.

http://jsfiddle.net/mg8g138x/

    app.directive('validation', function ($timeout) {

        return {
            restrict: 'AE',
            require: 'ngModel', 

            link: function (scope, element, attrs, ngModel) {
              if (!ngModel){
                return;          
              }

              scope.old= function(){
                alert("old")
              } 
             //attrs.$set('ngClick', 'new(this.form)');
              scope.new= function(form){
                alert("new");
                console.log(form)
              }                  

           }

        };
    });

Answer №1

There is a solution that involves creating a function to handle the use cases of two other functions you need to implement. For example, if you want function x to be triggered at the start and then function y to be triggered after a certain action, these can be called within the old() function.

I would advise against changing attributes, but if you still want to proceed, here is one way you could approach it:

app.directive('validation', function ($timeout) {

            return {
                restrict: 'AE',
                require: 'ngModel', 

                link: function (scope, element, attrs, ngModel) {
                  if (!ngModel){
                    return;          
                  }

                  scope.previous= function(){
                    alert("old")
                  }

                 scope.old= scope.previous 

                  scope.new= function(form){
                    alert("new");
                    console.log(form)
                  }
                 // This action should ideally be done within a separate function after an event or using $emit/$broadcast instead of directly in the code.
                 attrs.$set('ngClick', scope.old = scope.new); 
               }

            };
        });

You may also find this Stack Overflow discussion helpful: attrs.$set('ngClick', functionName + '()'); no longer working in angular 1.2rc3

Answer №2

It seems that the issue with your new function not working is due to AngularJS already compiling the template and linking all directives before your link function runs.

If you want to make changes to the ng-click value for a new function, you will need to re-compile the directive to see the effect of that change.

You can explore the AngularJS $compile service to understand how it can be utilized: https://docs.angularjs.org/api/ng/service/$compile.

Instead of directly changing the ng-click to a new function, consider utilizing JavaScript's functional programming feature. You can combine the old and new functions into one single function and choose which function to call using parameters. Here is an example:

 // Sample code snippet
link: function (scope, element, attrs, ngModel) {
    if (!ngModel){
        return;          
    }

    scope.old = function(){
        alert("old");
    }

    scope.new = function(form){
        alert("new");
        console.log(form)
    }

    scope.current = scope.old; // Control which function is called
    scope.form = ''; // Parameter for function called via ng-click

    scope.binding_to_button = function(function_to_call, parameter) {
        function_to_call(parameter);
    }

    scope.current = scope.new;
    scope.form = form;
}

Instead of binding scope.new or scope.old directly to ng-click, bind scope.binding_to_button.

ng-click="binding_to_button(current, form)" 

This way, you can dynamically control which function is called and what parameters are passed to them through the click event using $scope.current and $scope.form.

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

Sending both an array and an image via Ajax in a single request

I need to send both JSON and file data to my PHP backend using an ajax call. Here is my current ajax call: $.ajax({ type: 'POST', dataType: 'json', data: jsonData, url: 'xxx.php', cache: false, suc ...

Getting the value of an anchor tag in Laravel and utilizing it within an input field

I am facing an issue where $emp->id provides the correct id, but when I try to get id={{$emp->id}} it doesn't work as expected. Can someone please help me with this problem? <a href="{{'/employee'}}?id={{$emp->id}}" type="button ...

Why does Javascript in Angular throw an exception when using value, match, and replace functions together?

I have a small JavaScript function that I would like to implement in an Angular service or controller. function cprCheck(frm) { var cpr = frm.cpr.value; if (cpr.match(/[0-9]{6}\-[0-9]{4}/)) { cpr = cpr.replace(/\-/g, ""); var chk = 0; ...

Prevent submission by deactivating the button if a file has not been

I need help implementing a solution to disable a submit button until a file is selected. I found a working example online, but I'm not sure if the issue lies with the script type. Here's the example I'm referring to: disable submit button u ...

Running npm build/deploy is not functioning properly and is throwing a "failed to compile errors" message

I attempted to use npm run deploy/build, but it was unsuccessful and resulted in an error in the terminal. As a novice in git and github, I am looking to upload the changes I made in my most recent commit to my github pages. However, no matter how many tim ...

When using nodejs with sqlite3, the first callback parameter returns the class instance. How can this be resolved in order to prevent any issues?

Exploring a TypeScript class: class Log { public id: number; public text: string; construct(text: string){ this.text = text; } save(){ db.run( `insert into logs(text) values (?) `, this.text, ...

Creating a responsive touch slider: tips and tricks

I am looking to transform my gallery into a touch slider specifically for mobile devices. To achieve this, I have created two sections - one for desktop and another for mobile. I am utilizing the display property in a media query but my slider is not res ...

Managing data with React JS: Setting state after resolving a promise

const [userData, setUserData] = useState([]); useEffect(() => { fetch("https://reqres.in/api/users?page=2") .then((response) => response.json()) .then(data => setUserData(data)); return () => { console.log( ...

Is there a way in Reactjs Material UI 5 (MUI5) to unselect only the star that was clicked, without affecting the rest of the stars in the

For instance: I selected the 3rd star on the rating component, but when I click on it again, all the previous stars disappear and it shows 0 stars. How can I make it so that if I click on the 3rd star a second time, only the 3rd star is removed, leaving ...

ng-repeat not functioning properly with custom tabs

Everything was working perfectly until I added ng-repeat to the content <ul> <li ng-class="{active:tab===1}"> <a href ng-click="tab = tab==1 ? a : 1">Tab1</a> </li> <l ...

Creating a React component with a reference using TypeScript

Let's discuss a scenario with a reference: someReference; The someReference is essentially a React component structured like this: class SomeComponent<IProps> { getData = () => {}; render() { ...some content } } Now, how c ...

Error message: Attempting to access a property that is undefined (specifically 'ref') in MUI

Has anyone encountered this error when trying to customize themes in MUI v5 using custom variants? I keep seeing this error message: https://i.sstatic.net/D7F0e.png TypeError: Cannot read properties of undefined (reading 'ref') at Select (/va ...

NVDA fails to announce the "dialog" when a Modal is launched

When testing this simple modal example, I noticed that although the role is set to dialog and focus is correctly received on the dialog container when it opens, NVDA fails to announce the word 'dialog' at the beginning. This issue has been report ...

Error: The navigation property is not defined - React Native

Utilizing Firebase in combination with react-native for user authentication. The main file is App.js which directs users to the Login component and utilizes two components for managing routes: Appnavigator.js to create a switchNavigator and DrawerNavigator ...

JavaScript array remains unchanged

I have a sample of JSON data saved in the "data" variable. Here is the FORMAT : { "0" : {"names":"Pooja, Trivedi"}, "1" : {"names":"Pooja, Rooster"} } My objective is to create a map that can calculate the frequency of each name: Pooja = 2 Triv ...

Chrome geolocation feature does not display the permission popup for JavaScript

After the latest Chrome update, we have noticed that the popup to Allow/Block accessing a user's location from a website is no longer appearing. We tested this on Edge, Firefox, and different mobile devices, where it seems to be working fine. Current ...

Is there a way to make this ajax request synchronous instead of asynchronous?

For some reason, the getCategory function is only returning either undefined or false. I've checked the data in the console and it seems to be there. However, I'm still uncertain about the most effective way to handle synchronous function calls. ...

Elevate your tooltips with Bootstrap 5: enabling hoverable tooltips and clickable links

At times, you may want to include clickable links in tooltips. I recently encountered this issue while using Bootstrap 5 and had trouble finding a solution. After some trial and error, I finally figured it out and wanted to share my findings. The standard ...

Differences between using "break + return" and simply "return" in

Currently, I am developing a nodejs Heap and ensuring top performance is key. The code snippet I have looks like this: while(true) if(x) do something return if(y) do ... return if(z) do ... else return Suggestions were made to me to incorporate ...

"Exploring the best method to utilize a for loop for updating an array of objects in

I'm looking to update a nested mongo document using a for loop with my node.js code below: //loop starts var update = { "rate":mainRate, "classifierCategories."+e+".rate":temiz[i].slice(0,2) }; classifier.update({"classifierS ...