问题
I am trying to reconcile using the following directive for changing a button's loading state via bootstrap js plugin:
.directive("btnLoading", function() {
return function(scope, element, attrs) {
scope.$watch(function() {
return scope.$eval(attrs.btnLoading);
}, function(loading) {
if (loading)
return element.button("loading");
element.button("reset");
});
};
This is working quite well as it controls the state of the button when necessary and adds the loading text as advertised. The issue I am running into is that when this directive is applied to a button as well as utilizing ng-disabled when the form is not valid, the button is enabled and not disabled as it should/used to be before I applied this directive to the button. My ng-disabled on the button is just:
ng-disabled="form.$invalid"
Is there a way to reconcile these two directives so the disabled state is not reset within the loading directive?
EDIT Based on your suggestion I ended up with the following code:
.directive("btnLoading", function () {
return function (scope, element, attrs) {
scope.$watch(function () {
return scope.$eval(attrs.ngDisabled);
}, function (newVal) {
//you can make the following line more robust
if (newVal) {
return;
} else {
return scope.$watch(function () {
return scope.$eval(attrs.btnLoading);
},
function (loading) {
if (loading) return element.button("loading");
element.button("reset");
});
}
});
};
})
I had to use a function to watch for changes on eval of ng-disabled otherwise it would only return the function of what it needed to evaluate for changes, not the value/changed value. Additionally then I added the watch for the btn loading to watch for the click/save event and once that changes then set the loading state. Not sure if this is the best option but that was the only working code I could figure out.
回答1:
You can listen to the ng-disabled
property in the parent's scope, and if it is disabled then just simply does nothing.
The trick is to watch on ngdisabled
property like this
scope.$watch(attrs.ngDisabled, function (newVal) {...
I want to shed some light on since I can't test your code without other pieces, you probably can do something like this:
.directive("btnLoading", function () {
return function (scope, element, attrs) {
//maybe you need just scope.$watch instead of scope.$parent.$watch. Depends on your impl.
scope.$parent.$watch(attrs.ngDisabled, function (newVal) {
//you can make the following line more robust
if (newVal === 'disabled' || newVal === 'true') return;
function () {
return scope.$eval(attrs.btnLoading);
},
function (loading) {
if (loading) return element.button("loading");
element.button("reset");
}
});
}
});
来源:https://stackoverflow.com/questions/18019963/angularjs-button-loading-state-directive-with-ng-disabled-directive