AngularJS - bug with ng-disabled? Not updating with new values
I created working plunker here for you, to check that scenario described above is working:
<div ng-controller="HomeCtrl">
<button type="submit"
ng-click="submit(something)"
id="coolButton"
ng-disabled="type === 0 || code === ''"
>Check-In</button><br />
<div>type: <input ng-model="type" type="number" /></div>
<div>code: <input ng-model="code" type="text" /></div>
<div>is type equal zero: {{type === 0 }}</div>
<div>is type code empty: {{code === '' }}</div>
</div>
<script type="text/javascript">
var app = angular
.module('MyApp', [])
.controller('HomeCtrl', ['$scope', function ($scope) {
$scope.something = function(sth){alert(sth)};
$scope.type = 0;
$scope.code = "";
}])
</script>
Important parts here are inside of the controller, where we explicitly init the code and type. Otherwise both will start with undefined/null.
Check it here
Also, I would strongly suggest to change that style of $scope.type, $scope.code. It could bring some surprising behaviour sooner or later...
We should use some kind of Model cluster, which represents some reference which could be easily passed and does have a dot (see: https://stackoverflow.com/a/21882900/1679310)
// controller
$scope.Model = {
type : 0,
code : '',
}
// directive ngDisabled in the view
ng-disabled="Model.type === 0 || Model.code === ''"
Daniel Jamrozik
Updated on August 06, 2022Comments
-
Daniel Jamrozik almost 2 years
I'm somewhat new to angular and have come across a very weird problem, I'm sure others have too.
Let's say that this is the code for my button:
<button type="submit" ng-click="submit(something)" id="coolButton" ng-disabled="type === 0 || code === ''" >Check-In</button>
So, basically if either type is 0 or code is nothing (no text), then this button will be disabled.
Now's here where my problem starts: If I load the page with
type = 0
andcode = ''
, then sure enough it's disabled. If, I change both of these values then of course the button will be enabled.However, if I change the values back to
0
and''
, then the button won't become disabled again. I know for a fact that the values are in fact 0 and '' as I've printed their values out on the page.What could be causing
ng-disabled
to not run the expression again?