无法在选择框中设置选定的值

时间:2017-11-20 12:24:27

标签: javascript angularjs materialize

// inside controller

$scope.newEngagement.subType = 3;

$scope.engagementSubTypeList = [ 
{ "subTypeId": 1, "subTypeName": "value1" }, 
{ "subTypeId": 2, "subTypeName": "value2" },  
{ "subTypeId": 3, "subTypeName": "value3" }, 
{ "subTypeId": 4, "subTypeName": "value4" },
];
<div class="col s12 m12 margin-top-2x" ng-show="isSubType">
        <label class="uppercase blue-grey-text text-darken-5 font-1-5x clear left">SELECT SUB TYPE </label>
        <select
                name="engagement_subtype"
                id="engagement_subtype"
                ng-model="newEngagement.subType"
                class="browser-default margin-top-x col s12 m8 clear">
            <option value="{{subTypeList.subTypeId}}"
                    selected="subTypeList.subTypeId == newEngagement.subType"
                    ng-repeat="subTypeList in engagementSubTypeList track by subTypeList.subTypeId ">
                {{subTypeList.subTypeName}}
            </option>
        </select>
    </div>

根据以上代码,应选择“value3”,但不会与我使用materialize选择框浏览器默认类相同。

2 个答案:

答案 0 :(得分:1)

可以使用ng-options尝试使用newEngagement.subType,并在$scope.engagementSubTypeList下分配<div class=""> <label class="uppercase">SELECT SUB TYPE </label> <select ng-options="subTypeList.subTypeId as subTypeList.subTypeName for subTypeList in engagementSubTypeList" ng-model="newEngagement.subType"> <option value="">Select One</option> </select> </div> 。应该工作。

$scope.engagementSubTypeList = [ 
{ "subTypeId": 1, "subTypeName": "value1" }, 
{ "subTypeId": 2, "subTypeName": "value2" },  
{ "subTypeId": 3, "subTypeName": "value3" }, 
{ "subTypeId": 4, "subTypeName": "value4" },
];

$scope.newEngagement = {};
$scope.newEngagement.subType = $scope.engagementSubTypeList[2].subTypeId;

和控制器

import { formatCss } from 'app-name/helpers/format-css';

答案 1 :(得分:0)

您可以使用以下代码。

<div class="col s12 m12 margin-top-2x">
<label class="uppercase blue-grey-text text-darken-5 font-1-5x clear left">SELECT SUB TYPE </label>
<select
name="engagement_subtype"
id="engagement_subtype"
ng-model="newEngagement.subType"
class="browser-default margin-top-x col s12 m8 clear">
<option value="{{subTypeList.subTypeId}}"
ng-selected="{{newEngagement.subType == subTypeList.subTypeId}}"
ng-repeat="subTypeList in engagementSubTypeList track by subTypeList.subTypeId ">
{{subTypeList.subTypeName}}
</option>
</select>
</div>

$scope.newEngagement = {};
$scope.newEngagement.subType = 2;//{"subTypeId":3};

$scope.engagementSubTypeList = [ 
{ "subTypeId": 1, "subTypeName": "value1" }, 
{ "subTypeId": 2, "subTypeName": "value2" },  
{ "subTypeId": 3, "subTypeName": "value3" }, 
{ "subTypeId": 4, "subTypeName": "value4" },
];

Demo

我的建议是避免在选择选项中使用ng-repeat。您将使用ng-option,它只是angularjs中的正确approch。