The ng-disabled directive in Angular JS is not effectively disabling a button

Why is the button not disabled?

var mainApp = angular.module('mainApp', []);
mainApp.controller('mainController', function ($scope) {
    $scope.form = {
        login: ''
    };
});
<form ng-controller="LoginAppCtrl as lc" ng-app="MTApp">
  <div class="login">
    <h1>LOG IN</h1>
  </div>
  <div>
    <div>User Name :</div>
    <div>
      <input type="text" name="tbUserName" required ng-model="lc.request.user">
    </div>
  </div>

  <div>
    <div>Password :</div>
    <div>
      <input type="text" name="tbPassword" required ng-model="lc.request.password">
    </div>
  </div>
  <div>
    <div>
      <button ng-click="lc.submitRequest()" ng-disabled="lc.request.user == '' || lc.request.password == '' ">Sign In</button>
    </div>
  </div>
</form>

I'm a beginner in Angular JS and I'm attempting to create a basic login form. If the login is successful, another form will be shown, if not, the login form will remain. Can someone provide some assistance? I am in need of some basic tutorials.

Answer №1

There are a few errors in your code that you need to address:

Firstly, the module declaration should match the ng-app attribute. Instead of declaring it as 'mainApp', it should be ng-app="mainApp".

Similarly, the controller declaration and ng-controller attribute should also match.

Secondly, if 'request' is an object, make sure to initialize it in your controller:

$scope.request = {};

Thirdly, ensure to check for undefined as well, not just an empty string:

ng-disabled="!request.user || !request.password"

Refer to this Fiddle for the complete code and HTML.

Answer №2

There are two ways to disable button functionality:

1) Without involving the controller object, you can disable the button based on the values in the text boxes. Give a name to the form element like:

<form name='form1'>
  <div>
    <div>User Name :</div>
      <input type="text" name="tbUserName" required ng-model="lc.request.user">
  </div>
  <div>
    <div>Password :</div>
      <input type="text" name="tbPassword" required ng-model="lc.request.password">
  </div>
  <div>
    <button ng-disabled="form1.$invalid">Sign In</button>
  </div>
</form>

2) Alternatively, you can disable the button based on an object defined in the controller:

If you have an object in your controller, for example:

$scope.user = {name:'', password:''}

Then you can use ng-model='user.name' and ng-model = 'user.password' for the input boxes. The submit button can be disabled using:

ng-disabled=" user.name === '' || user.password === '' "
<form>
  <div>
    <div>User Name :</div>
      <input type="text" name="tbUserName" required ng-model="user.name">
  </div>
  <div>
    <div>Password :</div>
      <input type="text" name="tbPassword" required ng-model="user.password">
  </div>
  <div>
    <button ng-disabled="user.name==='' || user.password===''">Sign In</button>
  </div>
</form>

Make sure the controller has the object defined:

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.user = {name:'',password:''};
});

Is this what you were looking for?

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

Error: The parent selector "&" cannot be used in top-level selectors. $::webkit-input-placeholder

I am facing an issue while trying to run a legacy create-react-app that utilizes Sass. Initially, when I ran npm start, I encountered the error 'Cannot find module sass', which resembled the message found in this stack overflow post. To resolve t ...

Are your file uploaders malfunctioning by saving empty image files?

I am currently working on a file uploader using JavaScript and Classic ASP. The process involves importing an image into a canvas, converting it to a base64 URL, and then sending that URL to the ASP script for decoding and downloading. Although my AJAX re ...

Encountering an issue while sending JSON data to a WebAPI that contains an image in bytes format - Receiving an error message stating: "The expression is too long or

My experience with JSON is limited, but I'm currently developing a web service that will receive JSON data from an iOS device and insert it into a database. However, I've encountered an issue with the size of the image byte data which is causing ...

Unusual trait of TrackballControls.target within the world of Three.js

My current project involves simulating a 3D distribution of galaxies. In this simulation, the galaxies are represented as points. question1.htm references galaxydata1.txt to calculate and load the galaxy positions: rawFile.open("GET", "galaxydata1.txt", ...

Adjusting Iframe Dimensions Dynamically with Javascript based on Anchor Location

I am experienced with handling this issue in flash, but I am struggling to figure out how to do it using Javascript and CSS. The problem involves an iframe that does not have an overflow property, and I need to modify its width/height. Is there a simple ...

Utilizing TypeScript to enhance method proxying

I'm currently in the process of converting my JavaScript project to TypeScript, but I've hit a roadblock with an unresolved TypeScript error (TS2339). Within my code base, I have a class defined like this: export const devtoolsBackgroundScriptCl ...

Having trouble with the sleep function in nodejs?

Hey there! I'm currently working on a Node.js function that sends requests using array.map. However, I'm facing a challenge with making the function wait for 4 minutes when an error occurs before sending the next request. I've attempted to u ...

Implementing a for loop with the $http.get function followed by the .then

Previously in Angular, I utilized .success in conjunction with $http.get... Within the .success, I could execute the following: $http.get('/Home/GetUser') .success(function (result) { $scope.users = result; if (result != null) { ...

Transforming AngularJS $http POST requests into GET requests

I came across a scenario where I needed to update the logo path in my application. So, I defined a route like this: Route::post('/updateLogo', 'CaptivePortalController@updateLogo'); After defining the route, I made a POST request as s ...

Utilizing Vue JS to showcase a pop-up block when hovering over a specific image

There are four images displayed, and when you hover over each one, different content appears. For example, hovering over the first image reveals a green block, while hovering over the second image reveals a blue block. However, the current logic in place i ...

express path variables are constantly loading

Despite seeing the dynamic id in the URL, I am facing an issue with the page continually loading. Below, you will find the route that HTML redirects us to and details about the database. // Route Parameter app.get('/detail/:id', (req, res) => ...

Function generator within a component

I have a class-based component and I need to declare a generator function for an API call inside it without using fetch.then. Below is the code snippet: class SearchField extends React.Component { componentWillUnmount() { this.props.clearSearchStat ...

Transitioning from AngularJS to Angular 2: Exploring Alternatives to $rootScope.$on

Our journey with the AngularJS project has begun on the path towards the modern Angular. The ngMigration utility advised me to eliminate all dependencies on $rootScope since Angular does not have a concept similar to $rootScope. While this is straightforw ...

Modify components in a directive template depending on the information in the scope

In my project, I am facing an issue with a directive nested within an ng-repeat. The ng-repeat item is passed to the directive and I am trying to generate a directive template or templateUrl with dynamic elements based on a key/value in the item. Specifica ...

aligning JSON information with JavaScript object

I am currently in the process of setting up a sample dataset in JSON format for a JavaScript tutorial that I'm going through. Here's how the data object looks in JavaScript: app.Book = Backbone.Model.extend({ defaults: { coverImage: ...

``What is the best way to include a JavaScript jQuery variable value within a PHP array

Let's consider the following scenario: var folderName = jQuery.trim($('#dirname').val()); var parentFolder = jQuery.trim($('#parent').val()); var dynamicUrl = '<?=$this->url(array('controller'=>'index ...

The values are not being displayed in the local storage checkbox

I attempted to transfer checkbox values to another HTML page using local storage, however they were not appearing on the other page Here is my page1 HTML code snippet: <input class="checkbox" type="checkbox" id="option1" name="car1" value="BMW"> ...

Troubleshooting script not detecting changes in form

I am currently implementing a script to detect any changes in the form fields and notify the user if there are any. However, instead of triggering the alert box as intended, a different JavaScript box is displayed. Despite my efforts, the script is not re ...

Ways to dynamically fetch data by merging the response outcome with a dynamic parameter from the route in Vue.js

For the first time, I have been tasked with dynamically retrieving object parameters from the URL parameter. I am aware that I can use this.$route.params.[somelink-parameter] to obtain the URL parameter, and I understand how to retrieve and store the respo ...

What is the best way to retrieve the first item in owl carousel's content?

I need help creating a slider with two sections: top and bottom. My goal is to display the content from the bottom slider on the top slider. I tried adding a class to the first item element, but it didn't work. If anyone knows how to target the first ...