为什么ng-disabled中的表达式不起作用?

时间:2015-01-30 13:33:34

标签: angularjs

这是什么:

ng-disabled="login == ''"

当输入字段login为空时,不禁用按钮?

<html ng-app="mainApp">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-route.js"></script>
        <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
        <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
        <link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" rel="stylesheet" />
        <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.js"></script>

    </head>    
    <body ng-controller="mainController">

        <div class="col-md-3">
            <div class="panel panel-default">
                <div class="panel-heading">
                    LOGIN
                </div>
                <div class="panel-body">
                    <form>
                        <div class="form-group">
                            <label for="login">Login</label>
                            <input type="text" class="form-control" id="login" ng-model="login">
                        </div>
                        <div class="form-group">
                            <label for="inputPassword">Passowrd</label>
                            <input type="password" class="form-control" id="password">
                        </div>
                        <button type="submit" ng-disabled="login == ''"  class="btn btn-primary">Login</button>
                    </form>
                </div>
            </div>
        </div>

        <script>
                            var mainApp = angular.module('mainApp', []);

                            mainApp.controller('mainController', function ($scope) {
                            });
        </script>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

在控制器中创建一个表单对象,它将保存每个模型属性/字段,然后检查字段(login)是否等于空字符串。

...
<input type="text" class="form-control" id="login" ng-model="form.login">
...
<button type="submit" ng-disabled="form.login === ''" class="btn btn-primary">Login</button>
....

<强>控制器

mainApp.controller('mainController', function ($scope) {
    $scope.form = {
        login: ''
    }
});

<强> JSFIDDLE