如何使用 AngularJS 根据选择更改更新对象数组

How to use AngularJS to update an object array based on a selection change

本文关键字:更新 对象 数组 选择 何使用 AngularJS      更新时间:2023-09-26

我有两个动态对象数组。一个用于颜色,一个用于公共汽车。目标是为总线指定颜色。因此,使用 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-repeatbus的颜色作为selectng-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

希望有帮助