Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use angluarJS to disable a button if a value is bigger than 255?

I want to use angularJS to disable a submit button if the textarea contains more than 255 letters. I dont use angularJS usually, so I dont really know how to do it. here is what i have:(HTML)

<tr>
    <td colspan="2" align="center">
        <textarea rows="5" cols="40" name="Messge" ng-model="message"></textarea>
    </td>
</tr>
<tr>
    <td align="center">Number of letters left: <span ng-bind="left()"></span>
    </td>
</tr>
<tr>
    <td align="center" colspan="2">
        <input type="submit" value="submit" ng-disabled="error" />
    </td>
</tr>

now here are the javascript files code:

angular.module('myApp', []).controller('userCtrl', function ($scope) {
    $scope.messge = '';
    $scope.error = false;
    $scope.incomplete = false;

    $scope.$watch('messge', function () { $scope.test(); });

    $scope.test = function () {
        if ($scope.messge.length > 255) {
            $scope.error = true;
        } else {
            $scope.error = false;
        }
    };
});

2nd file:

app.controller("myNoteCtrl", function ($scope) {
    $scope.message = "";
    $scope.left = function () { return 255 - $scope.message.length; };
});

3rd file:

var app = angular.module("myNoteApp", []);

I found these codes in W3Schools, Altough i cant seem to make the button disabled. Can anyone help me with that? And if there is an easier way to combaine them all toghter in 1 file it would be great. if you still didnt understood what i meant, then tell me and ill try to explian it in a better way. TL;DR : I want to make a button become disabled when a textarea text length is bigger than 255.

like image 406
Shaked Dahan Avatar asked Dec 13 '25 16:12

Shaked Dahan


1 Answers

You can do this all with angular expresions in html:

<tr>
    <td colspan="2" align="center">
        <textarea rows="5" cols="40" name="Messge" ng-model="message"></textarea>
    </td>
</tr>
<tr>
    <td align="center">Number of letters left: {{255 - message.length}}
    </td>
</tr>
<tr>
    <td align="center" colspan="2">
        <input type="submit" value="submit" ng-disabled="message.length > 255" />
    </td>
</tr>

Note how I also got rid of the left() function and replaced it with an angular expression. This means you can actually get rid of all your js files (or at least all that relate to this).

like image 103
David says Reinstate Monica Avatar answered Dec 15 '25 09:12

David says Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!