我在 Google 上搜索过,但找不到答案...
我有一个 md-select
,如下所示:
<md-input-container class="md-block" flex-gt-sm>
<label>Type</label>
<md-select ng-model="f.type" placeholder="Type" select-clear>
<md-option ng-repeat="f in ctrl.type" value="{{f}}">{{f}}</md-option>
</md-select>
</md-input-container>
ctrl.type
在我的 Controller
中看起来像这样:
this.type = ["type1","type2"];
我还将 md-select
值发送到对象数组,如下所示:
var data = {
kind: $scope.f.type,
};
然后我正在执行一个 http.post
,将 data
对象发送到 api。
现在这是我的问题。我希望当 md-select
为空,并且用户发送 data
对象时,而不是收到错误 Cannot read property 'type' of undefined
表示只是发送了数据,但它的值为 null
而不是 undefined
,然后当 md-select
填充后,它只是将值发送到 api。我该怎么做呢?我需要进行表单验证吗?有没有一种简单的方法可以做到这一点,因为我有大约 10 个必须发送的 md-select
。
谢谢。
最佳答案
您可以在 md-option 上方创建一个空/虚拟选项,例如
<option value='null'></option>
<option ng-repeat="f in type" value="{{f}}">{{f}}</option>
但我认为,浏览器中出现空元素是因为您没有初始化 f.type
。如果正确初始化 f.type
,您甚至不会获得该空元素及其 undefined
值。您可以如下所示进行初始化。
<select ng-model='f.type' ng-change='toggleSelection()' ng-init='f.type = type[0]'>
关于javascript - 无法读取未定义的属性(表单验证) - angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35873580/