无法读取属性';长度';未定义javascript的定义

无法读取属性';长度';未定义javascript的定义,javascript,html,angularjs,Javascript,Html,Angularjs,我想验证这些字段。当用户未在字段中输入任何内容并单击“提交”按钮时,无法对其进行验证 请参见下面的示例: $scope.validateFields = function(){ alert("Comments " + $scope.comments); //When fields are blank and click on submit, it shows undefined if($scope.comments === 'unde

我想验证这些字段。当用户未在字段中输入任何内容并单击“提交”按钮时,无法对其进行验证

请参见下面的示例:

    $scope.validateFields = function(){
            alert("Comments " + $scope.comments); //When fields are blank and click on submit, it shows undefined
              if($scope.comments === 'undefined'){
                 alert("comments are blank");//not printed
                 $scope.comments = 'undefined';
            }
            if( $scope.comments.length == 0){
              alert("comments length is zero"); //not printed
              $scope.comments = 'undefined';
            }

在上面的示例代码中,当单击submit按钮而不在comments字段中输入任何内容时,它不会输入if条件。当注释字段为空并单击提交按钮时,我想分配
$scope.comments='undefined'

使用下面的代码。您可以在加载控制器时初始化$scope变量

app.controller('myCtrl',function($scope,$http){

      $scope.validateFields = function(){
          if($scope.comments){
             alert("comments are blank");
        }
        if( $scope.comments.length == 0){
          alert("comments length is zero");
        }
//      alert("validate"+ $scope.comments.length); 
      } 

      function init() {
        $scope.comments = '';
      }

      init();


    });

检查

第一个问题是检查$scope.comments是否与未定义的字符串匹配,而不是检查它当前是否在给定范围内定义

if($scope.comments === undefined) {
    alert("comments are blank");//not printed
    $scope.comments = '';
}
注意,为了实现这一点,我刚刚删除了undefined周围的引号。您甚至可以使用速记来检查值是否为假。您可以在网上找到虚假值的完整列表,但其中有几个是空字符串或未定义的

if(!$scope.comments) {
    alert("comments are blank");//not printed
    $scope.comments = '';
}
testVar = undefined;
接下来,您可以通过使用这样的注释初始化$scope来完全避免这种情况

var app=angular.module("myApp",[]);
app.controller('myCtrl', function($scope,$http) {
    $scope.comments = '';

    $scope.validateFields = function() {
        alert("Comments " + $scope.comments);
        if(!$scope.comments){
            alert("comments are blank");
        }
        else {
            alert("comments exist");
        }
    }
});

检查空值的最佳方法是

if ( testVar !== null )
{
    // do action here
}
对于未定义的

if ( testVar !== undefined )
{
    // do action here
}
可以将变量指定为未定义

if(!$scope.comments) {
    alert("comments are blank");//not printed
    $scope.comments = '';
}
testVar = undefined;
如果($scope.comments==undefined),请参考第3行的
{

注意
undefined
周围没有引号。