我想根据范围更改禁用按钮。
这是我当前的指令代码:
function disabledButton(){
return {
restrict: 'EA',
priority:1001,
scope:{
isLoading: '=loading'
},
link:(scope, element, attrs, isLoading)=>{
scope.$watch('isLoading', () => {
element.attr('disabled', true);
});
}
}
}
我的网页:
<button type="submit" class="pull-right" disabled-button>Update</button>
我的控制器很简单:
$scope.loading = true;
但它不起作用。该按钮未禁用。
有什么解决办法吗?
JSfiddlehttps://jsfiddle.net/ssuhat/gp6tq0Lt/7/
link
和compile
不能一起工作。
在指令定义对象中,如果您只定义链接,这就像一个空编译函数的简写,其中包含一个空的 preLink
函数,其中包含 postLink
函数中的代码。一旦你定义了compile
,link
就会被 angular 忽略,因为compile
应该返回链接函数。
如果您只从 compile
返回一个函数,那么它将在链接后执行。
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>
尝试使用 AngularJS 提供的 ngDisabled 指令。
<button ng-model="button" ng-disabled="isLoading">Button</button>
使用 element.prop('disabled', true);
而不是 element.attr('disabled', true);
另外,请确保在$watch
语句中添加else语句以重新启用该按钮。