0

我有两个动态对象数组。一种用于颜色,一种用于公共汽车。目标是为总线分配颜色。因此,使用 ng-repeat 代码为每种颜色创建选择,然后使用 ng-change 调用 updatebus 函数,传入颜色 ID。但是,它不起作用。颜色 ID 始终未定义。

如何使用两个数组将颜色分配给总线?我究竟做错了什么?

我试着看看这个答案:getting the ng-object selected with ng-change

普朗克

<!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>
4

2 回答 2

1

您应该使用您的颜色作为bus您的颜色。这样您就可以完全访问每条总线的选定颜色。ng-repeatng-modelselect

<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

希望有帮助

于 2015-01-29T19:44:00.100 回答
1

这里有两个问题:

  • 你有一个错字: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;
};
于 2015-01-29T19:44:33.160 回答