Creating an AngularJS directive specifically for a certain <div> tag

Recently, I began learning angularjs and came across a script to change the font size. However, this script ended up changing all <p> tags on the entire webpage. Is there a way to modify the font size of <p> tags only within the <div class="items-list"> section?

myApp.directive('textSizeSlider', ['$document', function ($document) {
return {
    restrict: 'E',
    template: '<div class="text-size-slider"><span>Увеличение шрифта</span><input type="range" min="{{ min }}" max="{{ max }}" step="{{ step || 0 }}" ng-model="textSize" class="slider" value="{{ value }}" /></div>',
    scope: {
        min: '@',
        max: '@',
        unit: '@',
        value: '@',
        step: '@'
    },
    link: function (scope, element, attr) {
        scope.textSize = scope.value;

        scope.$watch('textSize', function (size) {
            $document[0].body.style.fontSize = size + scope.unit;
        });
    }
}

}]);

  <text-size-slider min="12" max="24" unit="px" value="18" step="0">

Answer №1

If you want to make changes based on a watch function in your code, you can target elements of a specific class name and apply the desired modifications. See the example below:

 scope.$watch('textSize', function (size) {
      var elementList = element[0].getElementsByClassName('items-list');
            elementList.style.fontSize = size + scope.unit;
   });

Answer №2

While using CSS is recommended for this task, here is a way to restrict it to the active scope:

scope.$watch(function() {
  return scope.textSize;
}, function(newTextSize, oldTextSize) {

  var paragraphs = element[0].querySelector('.items-list').getElementsByTagName('p');

  var length = paragraphs.length,
      p, i;

  for (i = 0; i < length; i++) {

    p = paragraphs[i];

    p.style.fontSize = size + scope.unit;
  };
});

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

I encountered difficulty accessing a different domain from the node server

I am currently in the process of integrating the PayUmoney payment gateway into my MEAN stack application. I have successfully retrieved all mandatory fields from the Angular controller to Node and even generated the Hash key. However, when attempting to r ...

Encountered a problem when trying to generate a fresh component within an Angular application

Whenever I attempt to execute nx g c @nrwl/angular:app Admin in order to generate a component for my angular application, this error message appears. ...

Tips for identifying when input fields have been altered within an AngularJS application

On my new page, users can input data without using a form. For example: <input type='text' ng-model='ExpReport.ReportName' /> <input type='text' ng-model='ExpReport.startdate' /> There is an exit button ...

Creating a series of spots arranged in a semi-transparent line using JavaScript for a unique canvas

My attempt at creating a highlighter is encountering issues with transparency The problem might be due to using lineCap=round, resulting in multiple dark spots appearing in a single line (which shouldn't happen). It's difficult to fully describe ...

When adding files through drag and drop, the FormData is including a blank file field in the sent

I am currently working on a photo upload page that has drag and drop functionality enabled. Below is the form code: <form id="Upload" method="post" action="sessionapi/UserPicture/Upload" enctype="multipart/form-data"> <input class="box__file ...

What is the process for transferring a file's contents to my server?

I am currently working on allowing users to import an OPML file that I parse server-side in my Rails application. However, I am facing difficulties as it appears that my server is not receiving the information correctly (neither the success nor error funct ...

Linking Google Form Data to a MongoDB Database

Looking to integrate Google form with mongodb for data collection. Need help setting it up using NodeJs. Any advice on how to approach this? ...

Animating the height in ng-show with AngularJS version 1.2

I'm attempting to implement a height animation with Angular JS 1.2. I have created a plunker that demonstrates the animation successfully for closing the item: http://plnkr.co/edit/YVtnXgjO3Evb6tz5DJOp?p=preview The crucial part of this implementati ...

Is there a way to prevent the omission of zeros at the end in JavaScript when using Number.toString(2)?

I am facing an issue while trying to reverse a 32-bit unsigned integer by converting it to a string first. The toString(2) function is causing the zeros at the end to be omitted, leading to incorrect output. This is my code: var reverseBits = function(n) ...

Unable to retrieve element using getElementById with dynamically assigned id

After researching on Google and browsing through various Stack Overflow questions (such as this & this), I have not been able to find a solution. I am currently working on validating dynamically generated rows in a table. The loop and alert functions a ...

Incorporating a HTML layout with a JS backdrop

I have successfully implemented a JavaScript background and now I want to apply this background across all my PHP files. The issue is that the HTML code either overlaps with the JS content or appears behind it. How can I resolve this? Below is the JS fil ...

What is the best way to organize table rows into a single column when the window is resized?

I am working on a table that has three pictures in a row, with 100% width. I want the table to be responsive and stack the pictures into one column when the space is limited. The issue I am currently facing is that the elements of the table do not stack i ...

Grab the SVG and resize it to a smaller scale

I have a small application built using Raphael.js that creates a node network with SVG and reorganizes it based on user selections. My goal is to capture the SVG image I've created and display it in a "mini-map" format at the bottom of the screen. Si ...

Transform a <td> into a table-row (<tr>) nested within a parent <tr> inside an umbrella structure

Similar questions have been asked in the past, but I still haven't found a solution to my specific inquiry. Here it is: I have a table that needs to be sortable using a JavaScript plugin like ListJS. The key requirement is that I must have only one & ...

Using Vue.js to increment a value in an array every time a new row is added

In Vue.js, I am attempting to increment an array value when adding a new row. However, I encounter the following error message: You may have an infinite update loop in a component render function. The JavaScript logic looks like this: new Vue({ el: ...

Trigger the execution of a Python script through a webpage with just the click of a button

I have a small web interface where I need to control a Python script that is constantly gathering data from a sensor in a while loop. Ideally, I would like the ability to start and stop this script with the click of a button. While stopping the script is s ...

Challenges arising with the express search feature

Currently, I am in the process of developing an API for a to-do application. I have successfully implemented the four basic functions required, but I am facing some challenges with integrating a search function. Initially, the search function worked as exp ...

When checking for errors with console.log(errors) in Ajax, it may return undefined due to server-side

I'm looking for a way to alert the user about validation errors coming from PHP. I am currently using Laravel 5.3 to build the form and Ajax to retrieve error messages. Below is my JavaScript code: $.ajax({ url: '/artistPost', typ ...

The font styles shift and vertical bars vanish when placed under images

I'm currently facing some challenges with the text placement beneath the images on my website that I am constructing: 1) The font for "Back to home page" unexpectedly changes from the specified style (Georgia, 0.9em) in Firefox but remains consistent ...

Why is there a CSS reference failure in Express and how can it be resolved?

Below, you'll find a simple express server I've put together: // check out my basic Express server var express = require("express"); var app = express(); var bodyparser = require("body-parser"); app.use("/public/", express.static("./public/")); ...