如何使用 AngularJS 根据选择更改更新对象数组
How to use AngularJS to update an object array based on a selection change
我有两个动态对象数组。一个用于颜色,一个用于公共汽车。目标是为总线指定颜色。因此,使用 ng-repeat 代码为每种颜色创建选择,然后使用 ng-change 调用 updatebus 函数,传入颜色 id。但是,它不起作用。颜色 ID 始终未定义。
如何为具有两个数组的总线分配颜色?我做错了什么?
我尝试查看此答案:使用 ng-change 选择ng对象
普伦克
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - combining two arrays</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js"></script>
</head>
<body ng-app="selectExample">
<script>
angular.module('selectExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.colors = [
{name:'black', id:'a'},
{name:'white', id:'b'},
{name:'red', id:'c'},
{name:'blue', id:'d'},
{name:'yellow', id:'e'}
];
$scope.buses = [
{name:'bus 1', colorid:''},
{name:'bus 2', colorid:''}
];
$scope.theBus = $scope.buses[1]; // red
$scope.updatebus = function(bus, id){
//alert(id); // undefined
$scope.theBus = bus;
bus.cid = id;
};
}]);
</script>
<div ng-controller="ExampleController">
<p>
Bus Color:
<div ng-repeat="bus in buses">
{{bus.name}}
<select ng-model="myColor"
ng-options="color.name for color in colors"
ng-change="updatebus(bus, color.id)">
<option value="">-- choose color --</option>
</select>
<p>
</div>
<div>
the bus "{{theBus.name}}" has color id "{{theBus.colorid}}"
</div>
</div>
</body>
</html>
这里有两个问题:
- 你有一个错别字:
bus.cid = id;
- 而你用
ng-change
表达没有任何意义:updatebus(bus, color.id)
.color
?哪个color
?有一大堆。
解决此问题的一种方法:
bus.colorid = id;
<select ng-model="myColor"
ng-options="color.id as color.name for color in colors"
ng-change="updatebus(bus, myColor)">
更新的Plunkr:http://plnkr.co/edit/571TY2dC8cmLSPA7AAIv?p=preview
或者只是将您的选择权限绑定到bus.colorid
(我会说这实际上是更好的方法,因为如果您的总线具有初始颜色值,它将允许下拉列表显示正确的值):
<select ng-model="bus.colorid"
ng-options="color.id as color.name for color in colors"
ng-change="updatebus(bus)">
$scope.updatebus = function(bus){
//alert(bus.name); // undefined
$scope.theBus = bus;
};
您应该使用ng-repeat
中bus
的颜色作为select
的ng-model
。这样,您就可以完全访问每辆总线的选定颜色。
<select ng-model="bus.color"
ng-options="color.name for color in colors"
ng-change="updatebus(bus)">
所有赋值都在 html 绑定中完成,ng-change
保留仅用于显示目的。
请看一下,我做了一些小的更改以使其工作:
http://plnkr.co/edit/SoBUK61121VrqT31Jihj?p=preview
希望有帮助
相关文章:
- 如何在 Firebase 的 Angular-Fire 中使用 $save() 来更新对象属性值
- Expressjs&集合中的MongoDB更新对象's数组
- Physijs更新对象质量
- 如何使用setAttribute更新对象中的一个值
- 在分析中创建或更新对象
- 从knockout.js中的下拉列表更新对象
- Grails richui自动完成将对象传递给函数或更新对象ID
- 我正在使用 $scope.$apply 在 http 调用后更新对象数组.谁能告诉我正确的方法
- 如何使用 AngularJS 根据选择更改更新对象数组
- 从新对象的属性更新对象的属性,但前提是新对象上的属性不是未定义的
- 角度.js从NG重复更新对象数据
- 删除 JavaScript 中的重复代码;更新对象传递到函数中
- javascript:通过递增 objectKeys 值来更新对象
- 根据输入更新对象数组
- 想要在回调中更新对象,给出正确的日志,但全局对象未更新
- 流星:如果值等于 X,则更新对象 1,否则更新对象 2
- 如何在 Javascript 中更新对象数组中每个对象的值
- 嵌套的 ng-repeat 不会更新对象
- 使用从 MongoDB 获取的新数据更新对象属性
- 按 $parent.$index 和$index更新对象$scope项