默认情况下,如何将 ng-model 值设置为空字符串

By Default, How to set ng-model value to an empty string

这是我的代码:

 <div ng-app="myApp" ng-controller="myCtrl">
    Name: <input ng-model="myInput.name" />
    age: <input ng-model="myInput.age" />

    <pre>
      {{myInput | json}}
    </pre>
  </div>

  <script type="text/javascript">
    angular.module('myApp', [])
      .controller('myCtrl', function($scope) {
        $scope.myInput = {};
      });
  </script>

默认情况下,空字符串不会设置为 ng-model。

默认情况下,如何将所有 myInput 值设置为 ""?

这是plnkr

更新:

假设有超过 100 个 myInput 字段。我必须手动将其设置为“ ”吗?

更新二:

Pankaj Parkar 指令运行良好。但当然,它将所有模型值设置为 ' '。仅当模型为空时如何将模型设置为空字符串?我检查了 attrs.value == undefined 但没有任何帮助。

您可以使用对象字面量来初始化您的变量myInput。这将确保它们在加载时设置为空字符串

$scope.myInput = {
      name: '', 
      age: ''
    };

编辑:如果要初始化$scope.myInput对象中的所有值,可以使用如下JS代码:

Object.keys($scope.myInput).forEach(function(key, index) {
   $scope.myInput[key] = '';
});

或者您可以使用一些库,例如 underscorelodash 来迭代 myInput 对象中的值。我假设 myInput 对象中所有值的数据类型都是 String。如果存在 Array 等其他数据类型,您可以在 forEach() 块中插入该逻辑并相应地初始化值。

有两种方法。

在控制器中:

.controller('myCtrl', function($scope) {
    $scope.myINput = {
        name: '',
        age: ''
    };
});

或在视图中

Name: <input ng-model="myInput.name" ng-init="myInput.name=''" />
age: <input ng-model="myInput.age" ng-init="myInput.age=''" />

您可以使用以下代码获取密钥:

var attributes = Object.keys(myInput);

for (i = 0; i < attributes.length; i++){
   myInput[attributes[i]] = '';  
}

然后遍历属性并将它们分配给空值,然后将它们重新分配回我的JSON对象。 我假设您的对象是 JSON 对象。

你可以有一个指令来负责将默认值设置为 ''

标记

input empty-input ng-model="myInput.name" /> <br> <br>
age: <input empty-input ng-model="myInput.age" />

指令

.directive('emptyInput', function($parse) {
    return {
      require: '?ngModel',
      link: function(scope, element, attrs, ngModel) {
        //ngModel should be there & it should be of type text
        if (angular.isObject(ngModel) &&
          (!attrs.type || attrs.type === 'text')) {
          var model = $parse(attrs.ngModel);
          model.assign(scope, '');
        }
      }
    }
});

其他你可以遍历对象并使每个 属性 到 ''。但这有局限性,对于某些 属性,您不想将值更改为 ''。那么指令方式比在循环中添加条件更可取。

Demo here

仅当模型为空时才将模型设置为空字符串

.directive('emptyInput', function ($parse) {
            return {
                require: '?ngModel',
                link: function (scope, element, attrs, ngModel) {
                    var ngModelGet = $parse(attrs.ngModel);
                    scope.$watch(attrs.ngModel, function () {
                        if (ngModelGet(scope) == undefined && angular.isObject(ngModel) && (!attrs.type || attrs.type === 'text')) {
                            var model = $parse(attrs.ngModel);
                            model.assign(scope, '');
                        }
                    });
                }
            }
        });