我知道堆栈中类似于我的问题。但不同的是,我在控制器中为我的下拉列表选择了硬编码,然后我希望下拉列表默认显示模型中的值。
HTML:
<div class="form-group">
<label class="col-md-3 control-label" for="talent.rating">Rating*</label>
<div class="col-md-9">
<select ng-model="talent.rating" validator="required" required-error-message="Rating is required" name="talent.rating" ng-options="obj.value as obj.text for obj in array"></select>
</div>
</div>
控制器:
myApp.controller('editTalentController', ['$scope', '$rootScope', 'talentResolved', 'accountResolved', 'talentServices', '$location', 'ngDialog', '$window',
function ($scope, $rootScope, talentResolved, accountResolved, talentServices, $location, ngDialog, $window) {
$scope.talent = talentResolved.data;
$scope.array = [{ value: '1', text: '1' }, { value: '2', text: '2' }, { value: '3', text: '3' }, { value: '4', text: '4' }, { value: '5', text: '5' }];
}]);
型号:
$scope.talent: Object
createdOn: "2017-02-03T00:58:20.0999066"
employee : Object
fromAccount : Object
id :130
inDate : "2017-02-01T05:30:00"
movedOutOfBench : false
outTill : "2017-05-02T05:30:00"
rating : 2
remark : "asd"
resumePath : ""
我做错了什么?请提供修复代码。
答案 0 :(得分:1)
找到了解决方案。
HTML:
<select ng-model="talent.rating" convert-to-number>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
控制器:
myApp.directive('convertToNumber', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
ngModel.$parsers.push(function (val) {
return val != null ? parseInt(val, 10) : null;
});
ngModel.$formatters.push(function (val) {
return val != null ? '' + val : null;
});
}
};
});
即使我尝试将值作为数字给出,如:
$scope.array = [{ value: 1, text: '1' }, { value: 2, text: '2' }, { value: 3, text: '3' }, { value: 4, text: '4' }, { value: 5, text: '5' }];, angular was considering it as string. Don't know why.
When inspecting from console,it was like - https://hastebin.com/ugatisazey.vbs
该指令帮助我解决了这个问题。