选择下拉ajax/对象映射

ng-select dropdown ajax/object mapping

本文关键字:对象 映射 ajax 选择      更新时间:2023-09-26

使用angular ng-select,寻找将select下拉菜单与基于作用域中对象的属性选择的已选选项链接起来的最佳实践/建议。

  1. 控制器保存一个对象,该对象(动物)有一个选定的猫
  2. cats (options)是从Ajax调用中加载的,使用任何"promise"类型的angular服务(demo中的$http)
  3. 当页面加载时,我希望选择的猫与动物相同。猫(希望看到最简单的路径双向映射)

这是活塞:http://plnkr.co/edit/bMj7678djgPoJbiTRceG?p=preview

服务/控制器JS .

selectDemo = angular.module('selectDemo',[]);
selectDemo.factory("cat", ["$http", "$log", function($http, $log){
  return {
    query: function(runAfter){
      $log.debug("Getting cats from service");
      return $http.get('getCats.json');
    }
  }
}]);
selectDemo.controller('SelectDemoCtrl', ["$scope", "$log", "cat", function($scope, $log, Cat){
  $scope.animal = {type: "Mammal", cat: {"id": 2, "name": "Simon", "breed": "Persian"}};
  Cat.query().then(function(data){
    cats = data.data;
    $scope.cats = cats;
  });
}]);
Html:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>
  <body ng-app="selectDemo" ng-controller="SelectDemoCtrl">
    <h1>AngularJS Select Dropdown</h1>
    <div id="data"></div>
    <form role="form">
       <select data-ng-model="animal.cat" data-ng-options="cat.name for cat in cats">
          <option value="">Select a cat</option>
       </select>
    </form>
    <p>You selected: {{ animal.cat }}</p>
  </body>
</html>

JSON响应对象:

[{"id": 1, "name": "Garfield", "breed": "Tabby"},
{"id": 2, "name": "Simon", "breed": "Persian"},
{"id": 3, "name": "Twix", "breed": "Mixed"}]

这是一个更新的plunk:

http://plnkr.co/edit/KTJt9602eD5Pgr1y7c9w?p =

预览

这里的问题是,从ng-options中选择的对象需要引用等于 ng-model引用的对象,因此需要在数组中查找对象。