HTML
<select class="form-control"
ng-model="campaign.CampaignTypeId"
ng-options="CampType.id as CampType.name for
CampType in CampaignTypeIds track by CampType.id" >
<option value="">Select campaign type</option>
</select>
的JavaScript
$scope.CampaignTypeIds = [{ id: "1", name: "Location" }, { id: "2", name: "Brand" }];
$scope.getSingleCampaignResponse = function (response) {//http get method gets the resposne
$scope.campaign= response
}
如果我将广告系列对象作为回复并且该对象具有 CampaignTypeId:1 ,但我无法将 CampaignTypeId 绑定到ng-model以进行选择选项
答案 0 :(得分:1)
诀窍是ng-options你必须像这样ng-options="CampType as CampType.name for CampType in CampaignTypeIds track by CampType.id"
。您可以在此plunker中看到它正常工作。您还可以将ng-model绑定到对象,例如ng-model="campaign"
。
标记:
<body ng-app="myApp" ng-controller="myCtrl">
<select class="form-control"
ng-model="campaign"
ng-options="CampType as CampType.name for
CampType in CampaignTypeIds track by CampType.id" >
<option value="">Select campaign type</option>
</select>
</body>
在控制器上:
angular.module('myApp', [])
.controller('myCtrl', ['$scope', '$timeout', function($scope, $timeout) {
$scope.CampaignTypeIds = [{
id: "1",
name: "Location"
}, {
id: "2",
name: "Brand"
}];
$scope.getSingleCampaignResponse = function(response) {
$scope.campaign = response;
}
//simulating request
$timeout(function() {
$scope.getSingleCampaignResponse({ id: "2" });
// or if you want like this
// $scope.getSingleCampaignResponse({ id: "2" , name : "brand"});
}, 2000)
}]);
注意超时是在2秒后模拟请求。