我是角色的新手,我正试图设置一个默认状态,以便在我的ng-model为null时选择。基本上我想在模型为空时将其设置为“无”。我尝试了下面的代码,但它没有用。
<select ng-init="item.carType | item.carType='none'" ng-model="item.carType">
<option value="none">None</option>
<option value="manual">Manual</option>
<option value="auto">Auto</option>
</select>
答案 0 :(得分:24)
试试这个:
<select ng-init="item.carType = item.carType || 'none'" ng-model="item.carType">
<option value="none">None</option>
<option value="manual">Manual</option>
<option value="auto">Auto</option>
</select>
那就是per the docs,这可能是对ngInit的误用。执行此操作的正确方法是使用控制器(或服务,如果它来自哪里)中的合理值初始化模型。
答案 1 :(得分:3)
H i,
我的想法是最好在应用程序而不是模板中执行此操作。
if(typeof $scope.item.carType==="undefined") {
$scope.item.carType="none";
}
或只是设置值
$scope.item.carType="none";
在使用您设置值的任何内容进行更新之前: -
$scope.item.carType="none";
$scope.item.carType=someasyncfunctionthatmighttakeawhileandthetemplateisrenderedbeforeitarrives();
答案 2 :(得分:3)
您可以使用ng-init
中的值进行求解<select ng-init="item.carType='none'" ng-model="item.carType">
<option value="none">None</option>
<option value="manual">Manual</option>
<option value="auto">Auto</option>
</select>
答案 3 :(得分:2)
我建议你这样做。
在控制器中创建一个函数,并检查$scope.item.carType == undefined
是否指定了默认值。
$scope.setDefaultValueForCarType = function () {
if($scope.item.carType == undefined) {
$scope.item.carType = "none";
}
}
这也可以。
<select ng-init="item.carType='none'" ng-model="item.carType">
答案 4 :(得分:2)
由于错误的情况,通常会发生ng-model="item.carType"
与任何选择选项键都不匹配。
例如:item.cartType
是"Manual"
但是在选项中你有一个选项<option value="manual">Manual</option>
在这种情况下它不起作用,在控制台输出中你会看到这样的东西:<option value="? string:Manual ?"></option>
因此,要么更正您的数据模型,要么更正您的选择选项值:
<option value="Manual">Manual</option>
答案 5 :(得分:1)
您正在寻找的是未定义的。
如果值未定义,当选择“none”时,是否需要一个值转到数据库?
如果发送空白是可以接受的,您可以考虑以下事项:
<select ng-model="item.carType">
<option value="">None</option>
<option value="manual">Manual</option>
<option value="auto">Auto</option>
</select>
这允许您传入一个值,并使用相同的表单进行编辑和新记录。
答案 6 :(得分:0)
基于Rob Sedgwick的想法,在一个紧要的截止日期我没有使用$scope
所以使用控制器作为语法。
loadStates(); //this calls my function for my code
// this is based on what Rob S. is doing with $scope
if(typeof vm.scriptQuestion.statecode ==="undefined") {
console.log('in');
vm.scriptQuestion.statecode = "AA"; // "AA" happens to be the value of the default name for All of my States that is then displaying "ALL" now when before it was blank
}
这是我的选择(是的,这是做角度选择框的垃圾方式,因为ng-repeat对于选择非常有限)
<select id="States" ng-model="vm.scriptQuestion.statecode">
<option ng-repeat="state in vm.states" value="{{state.StateCode}}">{{state.StateName}}</option>
</select>
答案 7 :(得分:-1)
我对您的代码进行了以下更改,现在应该可以使用了。我已删除ng-init=""
中的第二部分,并将无选项值设置为undefined
。
<select ng-init="item.carType='none'" ng-model="item.carType">
<option value=undefined>None</option>
<option value="manual">Manual</option>
<option value="auto">Auto</option>
</select>