1

这是一个简单的 Angular 示例:

<!DOCTYPE html>
<html ng-app="GenericFormApp">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>    
</head>
<body ng-controller="GenericFormCtrl as ctrl">    
    <div>
        Model: {{ctrl.model}}
    </div>
    <div>
        <input ng-model="ctrl.model" />
    </div>
    <div>
        <input type="button" value="Alert model" ng-click="ctrl.showModel();" />
    </div>
    <script>        
        angular.module("GenericFormApp", [])
            .controller("GenericFormCtrl", [function () {               
                this.showModel = function () { alert(this.model); };
            }])        
    </script>
</body>
</html>

上面展示了如何将输入绑定到模型,这是 Angular 的一个基本特性。

它还允许用户弹出一个带有输入内容的模式对话框。这工作正常,除非输入为空。

在这种情况下,它显示“未定义”。

当然,我可以简单地编写一行代码,将模型的初始值设置为空白字符串,但这并不是特别实用,因为在我的实际应用中,有很多输入,用户可能会留下任意数量的他们空白。

简而言之,我想知道如何做到这一点,以便 Angular 知道一个空白输入应该在模型中包含一个空白字符串。

4

2 回答 2

2

我会使用自定义指令来扩展默认输入指令行为。因此,如果输入具有模型,则该指令将检查该模型是否未定义,如果是,则为其分配一个空字符串值。

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<div ng-app="GenericFormApp" ng-controller="GenericFormCtrl as ctrl">    
    
    <input ng-model="ctrl.model" /> {{ctrl.model}}<br>
    <input type="button" value="Alert model" ng-click="ctrl.showModel();" />
    
    <script>        
        angular.module("GenericFormApp", [])
            .controller("GenericFormCtrl", [function () { 
                this.showModel = function () { alert(this.model); };
            }])   
            .directive("input", function($parse) {
                return {
                    link: function(scope, element, attr, ngModelController) {
                        if (attr.ngModel) {
                            var model = $parse(attr.ngModel);
                            if (typeof model(scope) === 'undefined') {
                                model.assign(scope, '');    
                            }
                        }
                    }
                };
            });
    </script>
</div>

于 2015-09-14T21:54:08.503 回答
0

我同意@Claies,但是,如果您需要某些特定属性,您可以使用 ng-init:

<input type="text" ng-init="ctrl.model = ctrl.model || ''" ng-model="ctrl.model"/>

或创建一个特定的指令,如“auto-init”或类似的,而不是直接在输入元素上。

于 2015-09-14T22:10:34.647 回答