AngularJS:json从http请求

时间:2016-02-26 11:39:03

标签: angularjs json autocomplete httprequest

我是angularjs的新手并想知道我的方式。我想从$ http:

获得一个JSON
{"theItems":[{"name":"blah","description":"blah blah"},{...},{...}]}

(item.name,item.description)并在自动填充输入中显示名称供用户选择。

JSON是一个完整的对象,我想将名称解析为自动完成输入,但不知道如何。在其他情况下,我可以使用ng-repeat来扫描JSON对象,但这里没有意义。

目前自动完成输入并没有真正发生,我不知道是否有东西被检索出来或问题是我仍然没有从json中解析出来的名字......请建议。

这是获取JSON的代码:

/*global angular */
angular.module("app").factory('getList', function ($http) {
    'use strict';
    return {
        retrieve: function () {
            $http.get(URL).then(function (response) {
                return response.data;
            });
        }
    };
});

这是自动填充的代码:

/*global angular */
angular.module('app').directive('autocomplete', function ($timeout) {
    'use strict';
    return function ($scope, getList, iElement, iAttrs) {
        iElement.autocomplete({
            source: $scope.theList,
            select: function () {
                $timeout(function () {
                    iElement.trigger('input');
                }, 0);
            }
        });
    };
});

这是控制器:

/*global angular */
angular.module("app").controller('theController', ['$scope', function ($scope) {
    'use strict';
    $scope.theList = function (getList) {
        return getList.retrieve();
    };
}]);

这是html部分:

Select: <input autocomplete>

jsfiddle:https://jsfiddle.net/rf693c8z/1/ jsfiddle中的项目是&#34;手工制作&#34;,而不是来自请求。

2 个答案:

答案 0 :(得分:0)

尝试使用Ui bootstrap类型头部功能及其指令。

<style> .typeahead-demo .custom-popup-wrapper { position: absolute; top: 100%; left: 0; z-index: 1000; display: none; background-color: #f9f9f9; } .typeahead-demo .custom-popup-wrapper > .message { padding: 10px 20px; border-bottom: 1px solid #ddd; color: #868686; } .typeahead-demo .custom-popup-wrapper > .dropdown-menu { position: static; float: none; display: block; min-width: 160px; background-color: transparent; border: none; border-radius: 0; box-shadow: none; } </style>
<script type="text/ng-template" id="customTemplate.html"> <a> <img ng-src="http://upload.wikimedia.org/wikipedia/commons/thumb/{{match.model.flag}}" width="16"> <span ng-bind-html="match.label | uibTypeaheadHighlight:query"></span> </a> </script> <script type="text/ng-template" id="customPopupTemplate.html"> <div class="custom-popup-wrapper" ng-style="{top: position().top+'px', left: position().left+'px'}" style="display: block;" ng-show="isOpen() && !moveInProgress" aria-hidden="{{!isOpen()}}"> <p class="message">select location from drop down.</p> <ul class="dropdown-menu" role="listbox"> <li ng-repeat="match in matches track by $index" ng-class="{active: isActive($index) }" ng-mouseenter="selectActive($index)" ng-click="selectMatch($index)" role="option" id="{{::match.id}}"> <div uib-typeahead-match index="$index" match="match" query="query" template-url="templateUrl"></div> </li> </ul> </div> </script> 
<div class='container-fluid typeahead-demo' ng-controller="TypeaheadCtrl">
   <h4>Static arrays</h4>
   <pre>Model: {{selected | json}}</pre>
   <input type="text" ng-model="selected" uib-typeahead="state for state in states | filter:$viewValue | limitTo:8" class="form-control"> 
   <h4>Asynchronous results</h4>
   <pre>Model: {{asyncSelected | json}}</pre>
   <input type="text" ng-model="asyncSelected" placeholder="Locations loaded via $http" uib-typeahead="address for address in getLocation($viewValue)" typeahead-loading="loadingLocations" typeahead-no-results="noResults" class="form-control"> <i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i> 
   <div ng-show="noResults"> <i class="glyphicon glyphicon-remove"></i> No Results Found </div>
   <h4>ngModelOptions support</h4>
   <pre>Model: {{ngModelOptionsSelected | json}}</pre>
   <input type="text" ng-model="ngModelOptionsSelected" ng-model-options="modelOptions" uib-typeahead="state for state in states | filter:$viewValue | limitTo:8" class="form-control"> 
   <h4>Custom templates for results</h4>
   <pre>Model: {{customSelected | json}}</pre>
   <input type="text" ng-model="customSelected" placeholder="Custom template" uib-typeahead="state as state.name for state in statesWithFlags | filter:{name:$viewValue}" typeahead-template-url="customTemplate.html" class="form-control" typeahead-show-hint="true" typeahead-min-length="0"> 
   <h4>Custom popup templates for typeahead's dropdown</h4>
   <pre>Model: {{customPopupSelected | json}}</pre>
   <input type="text" ng-model="customPopupSelected" placeholder="Custom popup template" uib-typeahead="state as state.name for state in statesWithFlags | filter:{name:$viewValue}" typeahead-popup-template-url="customPopupTemplate.html" class="form-control"> 
</div>





   angular.module('ui.bootstrap.demo').controller('TypeaheadCtrl', function($scope, $http) {
              var _selected;
              $scope.selected = undefined;
              $scope.states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Dakota', 'North Carolina', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']; // Any function returning a promise object can be used to load values asynchronously 
              $scope.getLocation = function(val) {
                  return $http.get('//maps.googleapis.com/maps/api/geocode/json', {
                      params: {
                          address: val,
                          sensor: false
                      }
                  }).then(function(response) {
                      return response.data.results.map(function(item) {
                          return item.formatted_address;
                      });
                  });
              };
              $scope.ngModelOptionsSelected = function(value) {
                  if (arguments.length) {
                      _selected = value;
                  } else {
                      return _selected;
                  }
              };
              $scope.modelOptions = {
                  debounce: {
                      default: 500,
                      blur: 250
                  },
                  getterSetter: true
              };
              $scope.statesWithFlags = [{
                          'name': 'Alabama',
                          'flag': '5/5c/Flag_of_Alabama.svg/45px-Flag_of_Alabama.svg.png'
                      }, {
                          'name': 'Alaska',
                          'flag': 'e/e6/Flag_of_Alaska.svg/43px-Flag_of_Alaska.svg.png'
                      }, {
                          'name': 'Arizona',
                          'flag': '9/9d/Flag_of_Arizona.svg/45px-Flag_of_Arizona.svg.png'
                      }, {
                          'name': 'Arkansas',
                          'flag': '9/9d/Flag_of_Arkansas.svg/45px-Flag_of_Arkansas.svg.png'
                      }, {
                          'name': 'California',
                          'flag': '0/01/Flag_of_California.svg/45px-Flag_of_California.svg.png'
                      }, {
                          'name': 'Colorado',
                          'flag': '4/46/Flag_of_Colorado.svg/45px-Flag_of_Colorado.svg.png'
                      }, {
                          'name': 'Connecticut',
                          'flag': '9/96/Flag_of_Connecticut.svg/39px-Flag_of_Connecticut.svg.png'
                      }, {
                          'name': 'Delaware',
                          'flag': 'c/c6/Flag_of_Delaware.svg/45px-Flag_of_Delaware.svg.png'
                      }, {
                          'name': 'Florida',
                          'flag': 'f/f7/Flag_of_Florida.svg/45px-Flag_of_Florida.svg.png'
                      }, {
                          'name': 'Georgia',
                          'flag': '5/54/Flag_of_Georgia_%28U.S._state%29.svg/46px-Flag_of_Georgia_%28U.S._state%29.svg.png'
                      }, {
                          'name': 'Hawaii',
                          'flag': 'e/ef/Flag_of_Hawaii.svg/46px-Flag_of_Hawaii.svg.png'
                      }, {
                          'name': 'Idaho',
                          'flag': 'a/a4/Flag_of_Idaho.svg/38px-Flag_of_Idaho.svg.png'
                      }, {
                          'name': 'Illinois',
                          'flag': '0/01/Flag_of_Illinois.svg/46px-Flag_of_Illinois.svg.png'
                      }, {
                          'name': 'Indiana',
                          'flag': 'a/ac/Flag_of_Indiana.svg/45px-Flag_of_Indiana.svg.png'
                      }, {
                          'name': 'Iowa',
                          'flag': 'a/aa/Flag_of_Iowa.svg/44px-Flag_of_Iowa.svg.png'
                      }, {
                          'name': 'Kansas',
                          'flag': 'd/da/Flag_of_Kansas.svg/46px-Flag_of_Kansas.svg.png'
                      }, {
                          'name': 'Kentucky',
                          'flag': '8/8d/Flag_of_Kentucky.svg/46px-Flag_of_Kentucky.svg.png'
                      }, {
                          'name': 'Louisiana',
                          'flag': 'e/e0/Flag_of_Louisiana.svg/46px-Flag_of_Louisiana.svg.png'
                      }, {
                          'name': 'Maine',
                          'flag': '3/35/Flag_of_Maine.svg/45px-Flag_of_Maine.svg.png'
                      }, {
                          'name': 'Maryland',
                          'flag': 'a/a0/Flag_of_Maryland.svg/45px-Flag_of_Maryla

答案 1 :(得分:0)

getList工厂需要返回httpPromise。

/*global angular */
angular.module("app").factory('getList', function ($http) {
    'use strict';
    return {
        retrieve: function () {
            //return promise
            return (
                $http.get(URL).then(function onFulfilled(response) {
                    //return data for chaining
                    return response.data;
                })
            );
        }
    };
});