Is there a way for me to retrieve the element that is linked to the ng-disabled attribute?

Is there a way to access the element with the ng-disabled attribute inside the function without passing it as a parameter?

Here is the HTML element:

<input class="needsDisabling" ng-disabled="isFieldDisabled()" type="text">

The isFieldDisabled function in controller:

What is the method to access the element with the ng-disabled attribute within this function?

$scope.isFieldDisabled = function () {
        // What can I do to access the element with the ng-disabled attribute here? 

        // if (element has class "needsDisabling")
        // return true;
}

I am seeking an alternative approach to passing the element as a parameter in the function.

JSFiddle

Answer №1

In order to maintain good coding practices in AngularJS, it is recommended to use ngDisabled with your model instead of manually manipulating DOM elements in controllers (#2). However, if necessary, you can still create a custom directive to handle the disabled property manually (#1):

angular.module('myApp',[])
.directive('myDisabled', [function () {
        var myDisabled = {
            restrict: 'A',
            scope: false,
            link : function(scope, element, attrs, ngModelCtrl){
                scope.$watch(function() {
                    return scope.$eval(attrs.myDisabled).apply(scope, element);
                }, function(val) {
                    element.prop('disabled', val);
                });
            }
        }
        return myDisabled;
}])
.controller('MyCtrl', ['$scope', function MyCtrl($scope) {

    $scope.isFieldDisabled = function (element) {
      return angular.element(element).hasClass('disabled');
    }
    
    $scope.inputs = [{}, { disabled: true }, {}];
    
    $scope.isInputDisabled = function (input){
      return !!input.disabled;
    };
    
}]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.angularjs.org/1.6.4/angular.js" ></script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    <h2>#1</h2>
    <input class="needsDisabling disabled" my-disabled="isFieldDisabled" type="text"/>
    <input class="needsDisabling" my-disabled="isFieldDisabled" type="text"/>
    <input class="needsDisabling disabled" my-disabled="isFieldDisabled" type="text"/>
    <h2>#2</h2>
    <div>
      <input type="text" ng-repeat="input in inputs" ng-disabled="isInputDisabled(input)" ng-model="input.value"/>
    </div>
  </div>
</div>

Answer №2

In AngularJS, passing the element to the controller's function is not possible. However, you can make use of the ng-class directive to handle both your class and disabled values based on each other.

ng-class="{needsDisabling: isDisabled}" ng-disabled="isDisabled"

There is no reason why you shouldn't approach it this way because;

  • If the class isn't dynamic, then using disabled="disabled" would suffice without needing ng-disabled.
  • If the class value is dynamically changing outside Angular's scope, then that aspect needs to be addressed and rectified.

Furthermore, creating a custom directive in AngularJS itself could provide another solution to tackle this issue, as suggested by someone here.

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

Retrieving information from a hyperlink or input field within a list using jQuery

I'm working with the following script : <script> $().ready(function(){ $('.request_list').click(function(){ requesting_dept = $('#requesting_department_name').val(); alert(requesting_dept); $. ...

Is there a quicker method to update the state of an array of objects?

Here is my React state example: const [questionList, setQuestionList] = useState([ { _type: "radio", answer: "", point: "", question: "", options: ["A", "B"], ...

How can one leverage Node JS to effectively manage events?

Is it considered a best practice to utilize events for communication between functions within ExpressJS? If so, what is the proper way to send arguments along with my emit event? ...

Managing two simultaneous web service calls in Angular 2

Dealing with two parallel web service calls can be tricky. Sometimes the first call goes through first, and other times it's the second one. The problem arises when the function in my second service requires data from the first service call. I attemp ...

Rearrange the entire div container by simply dragging and dropping it. (Shift the Pop-up Modal dialog box)

How can I make a Modal pop-up draggable and change the color of the "Ok" and "Cancel" buttons on hover using a single CSS class? .hidModal{ position: fixed; font-family: Arial, Helvetica, sans-serif; top: 0; right: 0; bottom: 0; ...

Having difficulty making Skrollr compatible with BootStrap 3 single page wonder

I am completely new to JavaScript, which is why I decided to use Skrollr. However, I have been facing some challenges in getting Skrollr to work properly on my webpage. I added the following code at the end of my page: <script type="text/javascript" sr ...

Learn the process of dynamically populating an HTML table with data using JavaScript and JSON

I have developed a code snippet to dynamically add an HTML table without using jQuery. The code serves as an application from the server to the client, where the client receives a JSON object to parse into a string. Here is how you can add an HTML table ...

Concentrate on a specific component within an overlay using jQuery

How can I focus on a specific area within an overlay when adding an item to the cart? I want to make the rest of the overlay darker and the targeted area more visible. See a quick mockup here: https://i.sstatic.net/UpJuc.png Here's the HTML code: & ...

Issue with resetting input forms in ReactJS

I have a simple form that seems to be clearing the rest of the fields every time I try to fill it. Additionally, validation errors are being displayed below each field instead of just one. How can this issue be fixed? Here is how the form looks before any ...

How can JavaScript transform Unicode strings?

<i class="icon">&#xe672;</i> This code will display an icon like this: > However, when I render it in Vue: <i class="icon">{{a}}</i> a = '&#xe672;' The result is  It displays as a string! ...

Manage image placement using CSS object-position

I have the following code snippet: img{ width: 100%; height: 1000px; object-fit: cover; object-position: left; } <!DOCTYPE html> <html lang="en"> <head> <meta charset ...

Shift attention away from AG-Grid

AG Grid is being used on a website and when a user clicks a cell, it becomes focused with a blue outline. I am looking to remove this focus when the user clicks on specific elements on the site, but I am unsure of how to achieve this. Is there a method or ...

Achieving a perfect circle can be accomplished by setting both the width and height to the same

Trying to make the height of an element equal to its width For example, aiming for a perfect circle Although the console displays equal values, the resulting height is noticeably greater than the width $('button').on('click', funct ...

Obtain decrypted information from the token

I am facing difficulty in retrieving decrypted user data for the current user. Every time a user logs in, they receive a token. After logging in, I can take a photo and send it to the server. Looking at my code, you can see that this request requires a to ...

Unable to utilize await within a then statement to make a subsequent API call in a React application

Here is my scenario: I am making a call to one API, and in the `then` section of that API call, I am making another API call. The output of the first API will be passed as input to the second API. await axios .post(process.env + '/certificates/uplo ...

What is the best way to insert a permanent script tag into the body of a Gatsby site? Can conditional rendering be used to control

As an illustration: - const nation = "USA" import chat from './utils/script'; // script is imported from a file if(nation === "USA") // utilized conditionally in the component { chat } else { console.log("Not USA") } inform me witho ...

Global asynchronous functionality can be enabled in JavaScript

Wouldn't it be convenient to have the option to enable async functionality in the global scope? This way, there would be no need to wrap all asynchronous operations within a function. I'm curious if this is achievable in browser JavaScript or per ...

No Backend Detected for Tensorflow.js in Node

I've been attempting to develop a Discord bot that utilizes the @tensorflow-models/qna library, but I've hit a roadblock for the past 4 hours. Every time I run the script below: const qna = require('@tensorflow-models/qna'); (async () ...

Encountering some difficulties while setting up my development tool (specifically webpack)

I have embarked on a journey to learn modern JavaScript with the help of Webpack and Babel. As a beginner in this field, my instructor is guiding me through the principles of modern JavaScript by building an app called Forkify - a recipe application. While ...

combine a pair of elements simultaneously

I recently developed a nested directive for a multitabbed form, and here is a simplified version: <outer> <inner heading="a" src="'a.html'" active="true"></inner> <inner heading="b" src="'b.html'"></inner ...