[英]Default value of select using ng-init
I am trying to set the default value for select box, but I have hard time trying to do it, and I have no idea what is wrong. 我正在尝试为选择框设置默认值,但是我很难尝试做到这一点,而且我不知道出什么问题了。 Here is my code 这是我的代码
<select class="form-control" ng-init="newQuestion.positionOnSurvey=vm.questionsPositions[0]" ng-model="newQuestion.positionOnSurvey">
<option ng-repeat="position in vm.questionsPositions track by $index" value="{{position}}">{{position}}</option>
</select>
vm.questionsPositions[0] = 5, so this is not a problem. vm.questionsPositions [0] = 5,所以这不是问题。 I am not initializing newQuestion in my controller, but it should be not a case with ng-init ? 我没有在控制器中初始化newQuestion,但是ng-init应该不是这种情况吗?
UPDATE: 更新:
Now I am initializing the field like this, but it is still not working. 现在,我正在像这样初始化该字段,但是它仍然无法正常工作。
vm.newQuestion = {};
vm.newQuestion.positionOnSurvey = vm.questionsPositions[0];
<select class="form-control" ng-model="vm.newQuestion.positionOnSurvey">
<option ng-repeat="position in vm.questionsPositions track by $index" value="{{position}}">{{position}}</option>
</select>
You should use controller to initialize the value and better way to create drop-down list using ng-options 您应该使用控制器来初始化值,以及使用ng-options创建下拉列表的更好方法
Like: 喜欢:
HTML: HTML:
<select class="form-control" ng-model="newQuestion.positionOnSurvey" ng-options="position for position in vm.questionsPositions"></select>
Controller: 控制器:
$scope.vm ={};
$scope.newQuestion ={};
$scope.vm.questionsPositions = [12,14];
$scope.newQuestion.positionOnSurvey = $scope.vm.questionsPositions[0];
so initial value in select list is 12 因此选择列表中的初始值为12
您可以尝试使用默认值在控制器中初始化$newQuestion.positionOnSurvey
,因此视图中的选择器将具有初始值。
The only appropriate use of
ngInit
is for aliasing special properties ofngRepeat
[...].ngInit
的唯一适当用法是为ngRepeat
[...]的特殊属性设置ngRepeat
。 Besides this case, you should use controllers rather thanngInit
to initialize values on a scope. 除了这种情况,您应该使用控制器而不是ngInit
来初始化作用域上的值。
According to the ngInit
API, I'd suggest setting the initial value of your selection on your controller. 根据ngInit
API,建议您在控制器上设置所选内容的初始值。
see: controller guide 请参阅: 控制器指南
<select class="form-control" ng-init="vm.newQuestion.positionOnSurvey=vm.questionsPositions[0]" ng-model="newQuestion.positionOnSurvey">
<option ng-repeat="position in vm.questionsPositions track by $index" value="{{position}}">{{position}}</option>
</select>
You are declaring "newQuestion" variable in vm object. 您正在vm对象中声明“ newQuestion”变量。 So, you can access that variable in html as "vm.newQuestion" 因此,您可以将HTML中的变量作为“ vm.newQuestion”访问
You sure that ng-options is not working? 您确定ng-options不起作用吗? This code should do the trick. 这段代码可以解决问题。
<select ng-model="vm.newQuestion.positionOnSurvey" ng-options="position for position in vm.questionsPositions"></select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.