Utilizing Directives for DOM Manipulation in AngularJS

At this moment, I have a functional Angular app that is working properly. However, I am currently performing DOM manipulation within my controller instead of utilizing directives as recommended. My concern is, how can I correctly implement this functionality using directives?

For instance, consider the following simple example:

<div id="container1"></div>

<button type="button" ng-click="changeSize(1)">Small</button>
<button type="button" ng-click="changeSize(2)">Medium</button>
<button type="button" ng-click="changeSize(3)">Large</button>

This setup triggers the changeSize method in my controller which looks something like this:

$scope.changeVideoSize = function(size) {
    switch (size) {

        case 1:
            resizeDiv("container1", "320px" , "240px");
        case 2:
            resizeDiv("container1", "640px" , "480px");
        case 3:
            resizeDiv("container1", "1280px" , "960px");
    }
}
function resizeDiv(id, width, height) {
    var elem = document.getElementById(id);
    elem.style.height = height;
    elem.style.width = width;
}

Answer №1

To enhance your website, you may want to consider implementing a custom directive like the one below:

angular.module('myApp.directives', []).
    directive('adjustSize', [function() {
        return function(scope, elm, attrs) {

            function resizeElement(id, width, height) {
                var element = document.getElementById(id);
                element.style.height = height;
                element.style.width = width;
            }

            elm.bind("click", function(){
                  switch (attrs.size) {
                        case 1:
                            resizeElement("container1", "320px" , "240px");
                        case 2:
                            resizeElement("container1", "640px" , "480px");
                        case 3:
                            resizeElement("container1", "1280px" , "960px");
                    }
            });
        };
  }]);

After defining the directive, update your HTML markup accordingly:

<div id="container1"></div>

<button type="button" adjust-size size="1">Small</button>
<button type="button" adjust-size size="2">Medium</button>
<button type="button" adjust-size size="3">Large</button>

Answer №2

@MDiesel, your example illustrates the use of a directive, but I believe there are some areas that can be improved. In my opinion, a directive should primarily be used for DOM manipulation or creating a reusable component with an API.

For a scenario where pure DOM manipulation is required and won't be reused, I would suggest the following approach:

angular.module('myApp.directives', []).
    directive('resizeable', [function() {
        return {
            // Consider using a URL for better readability/maintainability.
            template: '<div id="container1"></div>' +
                      '<button type="button" ng-click="changeSize(1)">Small</button>' +
                      '<button type="button" ng-click="changeSize(2)">Medium</button>' +
                      '<button type="button" ng-click="changeSize(3)">Large</button>',
            link: function(scope, element) {
                scope.changeSize = function (size) {
                     var containerElement = element.find('#container1');
                     switch (size) {
                         case 1:
                             containerElement.width(320);
                             containerElement.height(240);
                         case 2:
                             containerElement.width(640);
                             containerElement.height(480);
                         case 3:
                             containerElement.width(1280);
                             containerElement.height(960);
                     }
                }
            }                
        }
    ]);
  1. The directive is now self-contained, avoiding the use of document to manipulate the DOM which aligns better with the purpose of a directive.
  2. Utilizing ng-click for event handling enhances the clarity of the template compared to manually listening to click events.

If the intention is to make this directive reusable and handle multiple elements, that would require a different approach. Feel free to reach out for further details on that scenario.

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

Utilizing Javascript to share images from a public Facebook page to a user's timeline via the Facebook API

Can someone assist me with finding a way to share a photo from a public Facebook page to the user's timeline using JavaScript? Is it possible to achieve this with FB.api or FB.ui? I have successfully shared feeds to the timeline using FB.ui, but am no ...

How to address hover problems in D3.js when dealing with Path elements and updating tooltip information after brushing the focus

Seeking assistance with a Multi Series, Focus + Context D3 chart and hoping to address my main queries all at once. The questions that need resolving are: How can I prevent the tooltips I've generated from being affected by the hair-line (which t ...

What methods are available in JavaScript regex for validating city names?

var cityRegex = /^[a-zA-z] ?([a-zA-z]|[a-zA-z] )*[a-zA-z]$/; is the regular expression I attempted to create. However, it fails when inputting a city name like "St. Petersburg." Update: It seems challenging to create a perfect regex pattern for city name ...

Reboot the node.js server

As I delve into learning node.js, I decided to start with a basic example in a file named server.js: var http = require("http"); function onRequest(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("it&a ...

What's the best way to refactor the `await nextEvent(element, 'mousemove')` pattern in my code once it is no longer necessary?

Within my React component, the code includes the following: class MyComponent extends React.Component { // ... trackStats = false componentDidMount() { this.monitorActivity() } componentWillUnmount() { this.trackStat ...

retrieve information using Python in JavaScript

I am in the process of developing a website using Python, Javascript (JQuery), and AJAX. While I know how to initiate a Python script with Ajax, I am unsure of how to send data back to Javascript from Python. For instance, if there is an error in a form s ...

Bug Alert: Incompatibility between Angular $resource and PHP causing issues with Update and Delete functionalities

As a newcomer to both AngularJS and PHP, I have been struggling to find comprehensive documentation on using $resource to update records in a database. While I did come across a helpful tutorial here that covers most aspects of $resource usage, I am having ...

Sending data to mongodb using the fetch API and FormData method is a simple process that involves constructing

I have been trying to send data to mongoDB using the fetch API along with FormData, but encountering an error: POST https://xxxxxxxxxxxxxxxxxxxxxxxx/upload 500 (Internal Server Error) The form data in my EJS file appears as follows: <div id=" ...

Interacting between various components in separate files using React.js

Creating a page using React involves two Components with different functions. The first component, ProfileFill, is responsible for capturing form data. On the other hand, the second component, ProfileFillPercent, which resides in a separate file, calculate ...

Ensure that the callback response in the $.ajax() function is treated as JSON dataType

My code snippet: <script> $('#email').on('blur', function(){ email = $(tihs).val(); $.ajax({ type: "POST", url: "ajax.php", data: { 'email': email, ...

Organize elements with jQuery, remove, detach, clone, and append without worrying about memory leaks

I am facing a challenge with a parent div that contains approximately 300 child divs, each one containing an image and some text. I have an array with the necessary information to reorder these divs using references. However, whenever I loop through the a ...

Returning a JSON representation of a JavaScript object

In the process of working on a script, I encountered a situation where an $.ajax call had to invoke a function upon success, returning a JavaScript object in JSON format [object object]. However, despite being able to return a well-formatted string, access ...

In an effort to bring some flair to my React Hangman App, I am working on animating a collection

Challenge In my Hangman App, I am attempting to implement letter animations using react-spring. I want the letters from an array to fade in when loaded and fade out when removed by clicking on them. However, my previous attempts have resulted in laggy per ...

Creating enduring designs in Next.js

I've been diving into this amazing article and I'm puzzling over the implementation of persistence in Option 4. It seems like you would need to redefine the .getLayout method for each page. I'm uncertain about how nesting logic is handled fo ...

Is the ID "nodeName" specifically designated as reserved in the HTML5 language specifications?

I have an element with the following id: <span id="nodeName"></span> In my HTML code. Then, when using jQuery to do the following: $("#nodeName").html("someString"); I am getting an error in the console that says: Uncaught TypeError: Objec ...

How can I simulate mouse position in a UIWebView?

Can the mouse position (x,y) for HTML-5 elements on a UIWebView be programmatically set using stringByExecutingJavascript in order to trigger hover, mouse over, and other interactions? ...

What is the difference between achieving a mirror effect and a steel effect using Three.js?

When using three.js, I find myself a little confused about the concepts of metalness and roughness. Can someone explain the differences between metalness and roughness when applied to materials like mirrors and metals/steel? And furthermore, how can these ...

Is it better to include the Google Analytics code in the master page or on every individual page of an asp.net

Looking for a way to track every page on my website effectively. Should I insert the Analytics tracking code in each aspx page inherited from the master page, or is it sufficient to place it only in the master page to track all inherited pages? ...

Creating a conditional statement in jQuery that will append text to a specific DIV element after a form has been successfully

I currently have a form set up that is functioning properly, but I am looking to make some changes. Instead of redirecting the user to a new page with a success message upon submitting the form, I want the success message to be displayed in a div next to t ...

Save the text entered into an input field into a Python variable

Is there a way to retrieve the text from input fields that do not have a value attribute using Selenium? The issue is that these fields are populated automatically, possibly through JavaScript, upon page load and the text does not appear in the HTML source ...