gpt4 book ai didi

AngularJS 选择不绑定(bind)到 Ng 模型

转载 作者:行者123 更新时间:2023-12-04 23:20:53 25 4
gpt4 key购买 nike

我的 Angular 选择没有约束力。我可以告诉值是正确的,但选择没有更新。如果值存在,为什么不具有约束力?

<div ng-controller="MyController" ng-app>
<select class="form-control" ng-model="colorId"ng-options="color.id as color.name for color in colorList">
<option value="">--Select a Color--</option>
</select>
<input type="button" value="submit" ng-click="Select()"></input>
function MyController($scope) {
$scope.colorList = [{
id: '1',
name: 'red'
}, {
id: '2',
name: 'blue'
}, {
id: '3',
name: 'green'
}];

var colorId = 3;
$scope.colorId = colorId;
alert($scope.colorId);

$scope.Select = function () {
var colorId = 2;
$scope.colorId = colorId;
}
}

这是一个 fiddle :

http://jsfiddle.net/ky5F4/23/

最佳答案

执行 Select 时需要将 id 更改为字符串

$scope.Select = function () {
console.log('select fired');
var colorId = 1;
$scope.mySelection.colorId = colorId + "";
}

http://jsfiddle.net/bxkwfo0s/2/

接下来您应该使用对象的属性而不仅仅是范围变量,这将确保正确的模型绑定(bind)
ng-model="mySelection.colorId"

对象可能很简单
$scope.mySelection = {colorId : colorId };

关于AngularJS 选择不绑定(bind)到 Ng 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27302283/

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