2015-11-03 51 views
0

我想知道如何将搜索按钮连接到输入字段。用AngularjS ng-click api搜索

controllers.js

angular.module('weatherApp.controllers', []) 
.controller('weatherCtrl', function($scope, $http) { 

    $http.jsonp('http://api.openweathermap.org/data/2.5/find?q=' + $scope.SearchCity + '&type=like&APPID=&callback=JSON_CALLBACK')    
     .success(function(data){ 
      console.log('success'); 
      $scope.cities = data; 

    }); 

}); 

all.html

<input type="text" ng-model="SearchCity" placeholder="Search for city" /> 
<input type="submit" ng-click="Search" Value="Search" /> 

<tr ng-repeat="city in cities.list | limitTo: 10 | filter:SearchCity"> 
    <td>{{city.name}}</td> 
</tr> 

app.js

angular.module('weatherApp', ['weatherApp.controllers', 'ngRoute']).config(['$routeProvider', function($routeProvider){ 
    $routeProvider.when('/all', {templateUrl: 'templates/all.html', controller:'weatherCtrl'}); 
    $routeProvider.otherwise({redirectTo: '/all'}); 
}]); 

回答

0

尝试这样:

控制器:

.controller('weatherCtrl', function($scope, $http) { 

    $scope.cities = []; 

    $scope.callOpenWeatherMap = function(searchCity){ 
    $http.jsonp('http://api.openweathermap.org/data/2.5/find?q=' + searchCity + '&type=like&APPID=&callback=JSON_CALLBACK') 
     .then(function(data){ 
     console.log('success', data); 
     $scope.cities = data; 
    }).catch(function(error){ 
     console.log('error', error); 

    }); 
    }; 

}); 

HTML:

<input type="text" ng-model="searchCity" placeholder="Search for city" /> 
    <input type="submit" ng-click="callOpenWeatherMap(searchCity)" Value="Search" /> 

    <tr ng-repeat="city in cities.list | limitTo: 10 | filter:searchCity"> 
    <td>{{city.name}}</td> 
    </tr> 

UPDATE

要提高你的代码,你可以创建一个OpenWeatherMap服务,而将所有注资方式/调用OpenWeatherMap api:

服务:

.service('OpenWetherMap', function($http){ 

    this.find = function(searchCity){ 
    return $http.jsonp('http://api.openweathermap.org/data/2.5/find?q=' + searchCity + '&type=like&APPID=&callback=JSON_CALLBACK'); 
    }; 

}) 

控制器:

.controller('weatherCtrl', function($scope, OpenWetherMap) { 

    $scope.callOpenWeatherMap = function(searchCity){ 
    OpenWetherMap.find(searchCity).then(function(data){ 
     console.log('success', data); 
     $scope.cities = data; 
    }).catch(function(error){ 
     console.log('error', error); 
    }); 
    }; 

}); 
+0

我在mozilla console中得到了这个:success Object {data:Object,status:200,headers:headersGetter/<(),config:Object,statusText:“load”}。它没有列出即将搜索的城市 –

+0

尝试将此行更改为:console.log('success',data.data); – manzapanza

1

我可能会misund知道你在问什么,但你应该能够将你的jsonp调用包装在$scope.Search函数中?

+0

我相当新的编码和不知道你的意思包装的东西。例如,当我在搜索字段中编写斯德哥尔摩时,我希望它将输入数据放入$ scope.searchCity中。但我仍然不知道ng-click如何工作 –

+0

'$ scope.Search = function(){$ http.jsonp(...); }' – Lee

+0

我一直在与它斗争,因为我不知道如何将按钮连接到我的输入字段。这就是我要找的! :) –