Comparing the use of .on in a directive versus in a controller

When deciding between attaching a directive to an element or binding an event inside the controller, what is considered best practice?

Directive

<openread-more what-to-expand="teds-bets-readmore" />

myApp.directive('openreadMore', function () {
    return {
        restrict: 'AE',
        replace: false,
        template: '<a class="attach-event" what-to-expand="readmore1">Event</a></span>',
        link: function (scope, elem, attrs) {
            elem.on('click', function () {
                // attached code on click
            });
        }
    }
});

Simply attaching it inside the controller

homepageCtrls.controller('homepageCtrl', function ($scope, $http) {
    angular.element(document.querySelectorAll('.attach-event')).on('click', function () {
         // attached code on click              
    });
});

The second approach may be shorter and cleaner, but whether it is considered best practice remains uncertain.

Answer №1

When implementing event handling in AngularJS, it's best to utilize the ng-click directive.

<openread-more what-to-expand="teds-bets-readmore" ng-click="doSomeAction()" />

To handle the click event in the controller:

homepageCtrls.controller('homepageCtrl', function ($scope, $http) {
    $scope.doSomeAction = function() {
       // Add your logic here...
    };
});

Edit

If you find yourself binding different types of events, consider whether these events will have distinct behaviors based on the current view or application state. If so, register event handlers in the controllers. If not, and the behavior remains consistent, handle the events within the directive.

It's important to note that direct access to UI elements within controllers is discouraged. Controllers should be reusable components that can work across varying UI designs. For specific event binding requirements, consider using a directive like Angular UI's Event Binder.

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

What is the best way to implement setState in this scenario?

Receiving warnings in the console that say: Avoid changing state directly. Instead, use setState() method: react/no-direct-mutation-state When I tried changing this.state.turn = this.state.turn === 'X' ? 'O' : 'X'; to this.s ...

Is it common for the external template to remain incompletely compiled during the execution of the directive's link function?

Let's consider a hypothetical directive called myDirective: <my-directive></my-directive>. Once compiled, it should be replaced by an external template like this: <my-button>MyButtonLabel</my-button> This my-button is expe ...

Outdated syntax for req.param in Express is now deprecated

I encountered an error on Node.js while working with some JavaScript code. The error message says: express deprecated req.param(name): Use req.params, req.body, Below is the relevant code snippet: response.render('pages/' + displayPage, { ...

Transmitting unique characters, such as a caron symbol, via xmlhttp.responseText and encoding them with json_encode

I am struggling to retrieve data from a database that contains a special character (caron) and then pass it through xmlhttp.responseText using json_encode to fill textboxes. However, the textbox linked to the data with the special character (caron) is not ...

What is the best way to perform a deep sumBy operation with lodash?

var data= [{ "item_name": "Jumbo Combo", "item_key": "9lazhy15tp2fgo72", "item_price": 25, "quantity": 1, "ingredients": [{ "group_key": "fg1udvnz81qwpxtp", "key": "kcck54k7h3fzp5f0", ...

What is the process for refreshing a user's session from the backend following updates to their metadata?

Currently, I am utilizing Next.js on the client side, auth0 for authentication, and Django Rest Framework for the backend. By following Auth0's Manage Metadata Using the Management API guide, I successfully managed to set new metadata values (verified ...

JavaScript is not being loaded onto the client by Express

I am looking to incorporate requireJS into my client code. Here is my file structure: ProjectRoot |-server.js |-public/ |-index.html |-js/ |-app.js |-lib/ |-require.min.js |-underscore.js |-backbone.js ...

What is causing the Maximum call stack size exceeded error to occur without using .val()?

Can anyone help me figure out why I am getting the error message "Uncaught RangeError: Maximum call stack size exceeded" when trying to implement a follow feature using the follow button? Adding .val() to Meteor.users.update(Meteor.userId(), {$addToSet: {& ...

Designing an interactive 3D space using JavaScript

I'm currently developing an app that allows users to visualize different wallpapers in a 3D room setting. The concept involves placing the user inside a virtual space with four walls, where they can drag and look around, as well as change wallpapers v ...

Angular: presenting items in navigation bar post logging in

I am relatively new to AngularJS and I am experiencing difficulties in displaying the userInfo in my navbar and showing the Logout button only when I am logged in. 1) Currently, I am using ng-show to show the Logout button only when I am logged in, but t ...

How to retrieve data from a nested object within a JSON array using JavaScript

When I use Logger.log(response.data.phone), the following data is displayed in my log: [{label=work, primary=true, value=5558675309}, {label=work, value=6108287680, primary=false}, {value=6105516373, label=work, primary=false}] My goal is to have the two ...

Exploring the Diversity of Forms with Ajax and JQuery

$(document).ready(function () { $("#addrow").click(function () { var newRow = '<tr><td><input type="text" class="item_code form-control" placeholder="Item Code" name="item_code[]"></td><td><input type="text" ...

Issue: Please avoid using HTML tag <img>. Instead, utilize the Image component from 'next/image' - Next.js when working with styled components

While working with Next.js, I encountered an issue with the Image component. Unlike a regular HTML tag, the Image component requires a layout and doesn't offer the same level of control. Additionally, I found that it couldn't be used with framer ...

Angular 4 showcases the information stored within this dataset

The data returned from an API to my Angular 4 application is not to my liking. Here is an example of the JSON, where I am only interested in the coin and its price: Goal is to display this data on the page: Coin Price BTC $4,281.28 ETH $294.62 ...

Is it possible for me to access the ng-model's key instead of the value within ng-value?

I am in the process of configuring a radio selector using an array to send the key instead of the value back to the server. Here is the specific array being used: $scope.customer_types = ['a', 'b', 'c', 'd', ' ...

Identifying changes in value in any scenario, jQuery

When I click on a button and change the input value, I want an alert to display 'Ok Done', but it's not working as expected. The input value may contain both numbers and letters. $("#myTextBox").bind("change paste keyup", function() { ...

An issue occurred while testing with React-Native Testing Library/Jest, where the property 'TouchableOpacity' could not be read

I am currently in the process of conducting tests using jest and react-native testing. Unfortunately, I have encountered an issue where TouchableOpacity is not being recognized and causing errors. Card.test.js import Card from "../Card" import R ...

Javascript will not be utilized in version 3.8

I'm encountering a problem with the website . It seems like my javascript files are not functioning properly. I added them in the functions.php using wp_enqueue_script(). The browser inspector confirms that the correct files are being called, but the ...

Setting the width of individual Views within a ScrollView to adjust accordingly in React Native

Is there a way to ensure that the Views inside my horizontal ScrollView have the same dimensions as the ScrollView itself? I'd like to implement paging so that swiping takes me to the next View within the ScrollView. I attempted using width : "100%" b ...

Looking for a piece of JavaScript code that can effectively query a MySQL database and show the results when a

I need a solution for a combo box that will display a list of choices. When a user selects an option, I want JavaScript to execute a MySql query based on the selection and return a simple value to be shown on the page next to the combo box. The query will ...