AngularJS - ng-disabled 的错误?不更新新值

AngularJS - bug with ng-disabled? Not updating with new values

我是 angular 的新手,遇到了一个非常奇怪的问题,我相信其他人也遇到过。

假设这是我的按钮的代码:

<button type="submit" ng-click="submit(something)" id="coolButton" 
        ng-disabled="type === 0 || code === ''" 
        >Check-In</button>

因此,基本上如果类型为 0 或代码为空(无文本),则此按钮将被禁用。

现在我的问题开始了:如果我用 type = 0code = '' 加载页面,那么肯定它被禁用了。如果,我更改了这两个值,那么当然会启用该按钮。

但是,如果我将值改回 0'',则该按钮将不会再次变为禁用状态。我知道这些值实际上是 0 和 '',因为我已经在页面上打印了它们的值。

什么可能导致 ng-disabled 不再 运行 表达式?

created working plunker here 为您检查上述情况是否有效:

<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>

这里的重要部分在控制器内部,我们在其中显式初始化代码和类型。否则两者都将以 undefined/null.

开头

检查一下here

此外,我强烈建议更改 $scope.type、$scope.code 的样式。它迟早会带来一些令人惊讶的行为...

我们应该使用某种模型集群,它代表一些可以轻松传递的引用并且确实有一个点 (参见:)

// controller
$scope.Model = {
  type : 0,
  code : '', 
}

// directive ngDisabled in the view
ng-disabled="Model.type === 0 || Model.code === ''"