gpt4 book ai didi

javascript - 无法将值绑定(bind)到 ng-model 以在事件中选择选项

转载 作者:行者123 更新时间:2023-11-27 23:06:52 25 4
gpt4 key购买 nike

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 绑定(bind)到 ng-model 进行选择选项

最佳答案

诀窍是 ng-options 你必须这样写 ng-options="CampType as CampType.name for CampType in CampaignTypeIds track by CampType.id" 。您可以在 plunker 中看到它的工作原理。您还可以将 ng-model 绑定(bind)到一个对象,例如 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>

在 Controller 上:

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 秒后模拟请求。

关于javascript - 无法将值绑定(bind)到 ng-model 以在事件中选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36508932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com