Javascript 按按钮1.x时无法读取未定义的属性

Javascript 按按钮1.x时无法读取未定义的属性,javascript,angularjs,Javascript,Angularjs,很抱歉在这里问一个简单的问题。但我真的不知道如何修复它,也不知道为什么会出现这个错误:( 我使用angular 1.x得到了这个错误。我想在这里是关于当用户按下按钮而没有在表单中输入标题时发出警报 这是我的代码,我让它更简单,顺便说一句:D index.html <div class="form-group"> <label for="">Title</label> <input type="text" ng-model="shipmen

很抱歉在这里问一个简单的问题。但我真的不知道如何修复它,也不知道为什么会出现这个错误:(

我使用angular 1.x得到了这个错误。我想在这里是关于当用户按下按钮而没有在表单中输入标题时发出警报

这是我的代码,我让它更简单,顺便说一句:D

index.html

<div class="form-group">
    <label for="">Title</label>
    <input type="text" ng-model="shipment_template.title" class="form-control">
</div>



<button ng-click="check">Check This</button>
问题是,当我填充输入时,我会在控制台中获得
成功
,但当我没有填充时,我不会得到任何警报,相反,我得到了这个错误

无法读取未定义的属性“title”

首先,我尝试不使用typeof,使用length,但它给出了相同的错误:(


对不起,我的英语不好,我希望你们都能帮我解决这个问题:-D

你们可以像这样在你们的控制器中初始化你们的
发货模板:

shipmentTemplate.controller.js

if (typeof $scope.shipment_template.title == 'undefined') {

    console.log("success")
} else {

    alert("Please fill the title")
}
$scope.shipment_template = {'title':''};

只需将模型传递到您的检查函数中,即可完成以下操作:

HTML:


工作代码:

您需要在控制器中定义
shipping\u模板
,使用
$scope.shipping\u template={}
Oww是的,它可以工作:D,谢谢,先生!或者只需将ng模型值(
shipping\u template.title
)传递给ng click函数(见我下面的例子)哦,它也有效,我不知道这个问题是否可以用很多方法解决。谢谢你,先生:-DSo有很多解决方案,但最佳实践是@Satpal建议的。先生,我认为它应该
if(input)
而不是
if(!input)
XD。但是谢谢你用这种方法解决我的问题,不客气:)这是我最初的想法,但您最初的逻辑是
typeof$scope.shipping\u template.title==“undefined”
,这意味着
“如果标题未定义,那么console.log success”
。出于某种原因,我假设这是您的预期行为。无论如何,我更改了答案以反映正常验证的外观(如果有输入,则输出成功-如果没有输入,则提示用户填写输入)
<div class="form-group">
 <label for="">Title</label>
 <input type="text" ng-model="shipment_template.title" class="form-control">
</div>

<button ng-click="check(shipment_template.title)">Check This</button>
  $scope.check = function(input) {
    if (input) {
      console.log("success");
    }
    else {
      alert("Please fill the title");
    }
  }