Reputation: 7656
I want to make disabled a button based on scope changes.
Here is my current directive code:
function disabledButton(){
return {
restrict: 'EA',
priority:1001,
scope:{
isLoading: '=loading'
},
link:(scope, element, attrs, isLoading)=>{
scope.$watch('isLoading', () => {
element.attr('disabled', true);
});
}
}
}
my html:
<button type="submit" class="pull-right" disabled-button>Update</button>
My Controller just a simple:
$scope.loading = true;
But it's not working. The button is not disabled.
Any solution?
JSfiddle https://jsfiddle.net/ssuhat/gp6tq0Lt/7/
Upvotes: 1
Views: 1450
Reputation: 803
link
and compile
do not work together.
In the directive definition object, if you only define link, that's like shorthand for having an empty compile function with an empty preLink
function with your code in the postLink
function. As soon as you define compile
, link
is ignored by angular, because compile
should return the linking functions.
If you only return one function from compile
, then it'll be executed post link.
angular.module('app', [])
.controller('myctrl', function($scope, $timeout) {
$scope.loading = true;
$scope.change = function() {
$scope.loading = !$scope.loading;
}
})
.directive('disabledButton', function() {
return {
restrict: 'AE',
scope: {
isLoading: '='
},
compile: function() {
return function(scope, element, attrs) {
console.log(element);
var loading = scope.isLoading;
scope.$watch('isLoading', function(a, b) {
element.attr('disabled', a);
});
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="myctrl">
<button ng-click="change()">dsa</button>
<div class="row">
<button is-loading="loading" disabled-button>Update</button>
</div>
</div>
</div>
Upvotes: 1
Reputation: 1582
Use element.prop('disabled', true);
instead of element.attr('disabled', true);
Also please make sure to add else statement in the $watch
statement to re enable the button.
Upvotes: 0
Reputation: 1582
Try using the ngDisabled directive provided by AngularJS.
<button ng-model="button" ng-disabled="isLoading">Button</button>
Upvotes: 0