button with ng-disabled always enabled

2019-02-22 00:46发布

I'm trying to conditionally enable/disable my Save button using ng-disabled:

<button type="button" title="Save Changes" ng-click="onSaveChanges()"
        ng-disabled="{{!data.modified}}">
  Save
</button>  

I have a $scope.data.modified variable that changes to true when my data has been modified. Regardless whether that is true or false, the Save button is enabled. Element inspection reveals that the value of ng-disabled toggles between "true" and "false" as expect but the button is always enabled.

2条回答
贪生不怕死
2楼-- · 2019-02-22 01:23

Element inspection reveals that the value of ng-disabled toggles between "true" and "false" as expect but the button is always enabled.

Remove the double curly brackets ({{ }}) from the Angular expression:

<button type="button" title="Save Changes" ng-click="onSaveChanges()"
        ̶n̶g̶-̶d̶i̶s̶a̶b̶l̶e̶d̶=̶"̶{̶{̶!̶d̶a̶t̶a̶.̶m̶o̶d̶i̶f̶i̶e̶d̶}̶}̶"̶>̶
        ng-disabled="!data.modified">
  Save
</button>

The double curly brackets convert the Angular expression to a string. In JavaScript, the string "false" is truthy. Hence both strings "true" and "false" evaluate as truthy and the button is always enabled.

Directives which expect boolean values won't work.

See Why mixing interpolation and expressions is bad practice.

查看更多
可以哭但决不认输i
3楼-- · 2019-02-22 01:31

when you are using a angular js attribute (like ng-show, ng-hide, ng-disabled) it should be without the snake notation Ex.ng-disabled="!data.modified" . For other ordinary attribute like class, id you have to use it with the snake notation. Ex. class={{aVaribaleinControllerScope}}

查看更多
登录 后发表回答