Pez
Pez

Reputation: 1101

Enable/Disable button from controller on Angularjs

I have an HTML button option as the following,

<button ng-class="{'primaryButton':true}" type="button" id="modalCreateBtn" "ng-hide="false" class="btn btn-group mm-btn-save primaryButton" ng-click="addSegments()">CREATE</button>

There is no ng-disable option in the above button option. Is this possible to enable/disable button with buttonId on controller? Also, I dont want to add disable option on HTML view. Instead I want to control it via scripts. Is this possible?

Upvotes: 14

Views: 42872

Answers (3)

tyne
tyne

Reputation: 115

Have you tried using ng-if ?

Controller :

$scope.setUploadMode = function (stats) {
    if (stats == 4) {

        $scope.selectMe = false;

    } else { alert("No"); $scope.selectMe = true;  }
};

$scope.hello = function () {
    alert("YEY");
};

HTML :

div class="radio">
<label>
    <input type="radio" name="appendCreateMode" ng-disabled="uploadMode != 2" ng-click="setUploadMode(4)" />Append Folder
</label>
</div>
<button ng-model="button" ng-disabled="selectMe" ng-click="hello()">Button</button

Upvotes: 0

Gabriel Kohen
Gabriel Kohen

Reputation: 4286

Have you looked into ngDisable? You can have an ngModel and change it from the controller. Like the documentation example says here:

<span  ng-controller="MyController as myController">
  <label>Click me to toggle: <input type="checkbox" ng-model="myController.checked"></label><br/>
  <button ng-model="button" ng-disabled="myController.checked">Button</button>
</span>

And the JS:

angular.module('controllerAsExample', [])
  .controller('MyController ', function(){
      this.checked = false;
 //   this.checked = true;
  });

Upvotes: 15

Alhuck
Alhuck

Reputation: 1029

Using ng-disabled is the best practice to enable/disable a button, but you can also achieve it in the controller without adding disabled property to your HTML view with this scripts,

angular.element(document.getElementById('yourButtonId'))[0].disabled = true;

In your case,

angular.element(document.getElementById('modalCreateBtn'))[0].disabled = true;

Plunker

Hope this helps!

Upvotes: 12

Related Questions