ng-select下拉ajax /对象映射

时间:2014-06-03 20:50:01

标签: javascript ajax angularjs angularjs-directive

使用角度ng-select,寻找最佳实践/建议,将选择下拉列表与根据范围内对象的属性选择的所选选项相关联。

  1. 控制器持有具有选定猫的(动物)
  2. 的对象
  3. cat(选项)是使用任何"承诺"从Ajax调用加载的。类型角度服务(演示中的$ http)
  4. 当页面加载时,我希望选中的cat与animal.cat相同(希望看到最简单的双向映射路径)
  5. 以下是plunker: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"}]
    

1 个答案:

答案 0 :(得分:1)

这是一个更新的插件:

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

这里的问题是ng-options中的所选对象需要引用ng-model引用的对象,因此需要在{{1}}中找到对象阵列。