AngularJs 选择 ng 选项不起作用

AngularJs select ng-options not working

本文关键字:不起作用 选项 ng 选择 AngularJs      更新时间:2023-09-26

我试图在AngularJS中进行选择,但没有成功。

我有两个对象:

动物类型

 $scope.animalTypeArray = {idAnimalType:"xxx", name:"yyy"}; ...

动物

$scope.animal = new animalObj(); //This one is empty.
  this.idAnimalType,
  this.name,
  this.age ...

我想做的是显示一个 animalsType 列表,并将 idAnimalType 放入 Animal obj 的 idAnimalType 中。

我正在尝试这个:

<select  class="form-control select-primary" id="animalType" ng-model="animal.idAnimalType" ng-options="animalType.getName() for animalType in animalTypeArray track by animalType.getIdAnimalType()">

控制器:

//objectsdeclaration
$scope.animalType = new animalTypeObj();
$scope.animal = new animalObj();
$scope.animalTypeArray = new Array();
$scope.animalType;
//objects creation of animalType to show on the select
var animalType = new animalTypeObj();
animalType.construct(1,"Bird");
$scope.animalTypeArray.push(animalType);
var animalType = new animalTypeObj();
animalType.construct(2,"Insect");
$scope.animalTypeArray.push(animalType);

当我打印console.log($scope.animalTypeArray)时;对象数组显示为OK。

显示的 select 结果与数组的结果数量相同,但它们只打印空白字符,而不是预期名称。

我做错了什么?

你在寻找这样的东西吗?它是您要做的粗略版本...我即兴创作了动物类型Obj和动物Obj如下...

  function animalTypeObj(){
     var that = this;
     that.construct = function(type, name){
     that.type = type;
     that.name = name;
     }
     that.getName = function(){return that.name;}
     that.getIdAnimalType = function(){return that.type; }
}
function animalObj(){
     var that = this;
     that.idAnimalType = {};
     that.name = '';
     that.age = 0;
}

我跳过了

http://jsfiddle.net/c2zamajc/5/

希望它有帮助....

由于您没有提供太多代码,因此我认为您需要这样的东西:

    <select  class="form-control select-primary" id="animalType" ng-model="animal.idAnimalType"
      ng-options="animalType.idAnimalType as animalType.name for animalType in animalTypeArray">
   </select>