2017-03-31 31 views
0

我試圖通過搜索城市參數來修改城市參數,但我不認爲這是可以修改角度服務的方式。那麼我將如何能夠修改控制器中的服務參數?任何幫助將是驚人的!如何修改angularjs服務url paramer

HTML:

<section ng-controller="MainController"> 

    <form action="" class="form-inline well well-sm clearfix" > 
    <span class="glyphicon glyphicon-search"></span> 
    <input type="text" placeholder="Search..." class="form-control" ng-model="city" /> 
    <button class="btn btn-warning pull-right" ng-click="search()"><strong>Search</strong></button> 
</form> 
    <h1>{{fiveDay.city.name}}</h1> 
    <div ng-repeat="day in fiveDay.list" class="forecast"> 
     <div class="day"> 
      <div class="weekday"> 
       <p>{{ day.dt*1000 | date}}</p> 
       <!-- <p>{{ parseJsonDate(day.dt)}}</p> --> 
      </div> 
      <div class="weather"><img ng-src="http://openweathermap.org/img/w/{{day.weather[0].icon}}.png"/></div> 
      <div class="temp">{{day.weather[0].description}}</div> 
      <div class="temp">Max {{ day.main.temp_max }}°</div> 
      <div class="temp">Min {{ day.main.temp_min }}°</div> 
     </div> 
    </div> 
</section> 

JS:

var app = angular.module('App', []); 
app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) { 
forecast.city="orlando"; 
    forecast.success(function(data) { 
     $scope.fiveDay = data; 
    }); 
    }]); 
app.factory('forecast', ['$http', function($http) { 
var city = "orlando"; 
var key="a1f2d85f6babd3bf7afd83350bc5f2a6"; 
    return $http.get('http://api.openweathermap.org/data/2.5/forecast?q='+city+'&APPID='+key+'&units=metric&cnt=5') 
    .success(function(data) { 
     return data; 
    }) 
    .error(function(err) { 
     return err; 
    }); 
}]); 
+0

您的服務使用http shoudnn't獲取數據。它應該公開一個方法,服務的用戶可以用參數調用。該函數將使用http獲取並返回數據。閱讀有關服務的文檔。另請閱讀$ http文檔,其中解釋瞭如何安全地傳遞參數。 –

回答

0

城是你的可變部分ecast factory因此需要把它作爲函數的參數將是推薦

試試這個

var app = angular.module('App', []); 
app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) { 
    var city = "orlando"; 
    forecast.getWeatner(city).success(function(data) { 
     $scope.fiveDay = data; 
    }); 
}]); 
app.factory('forecast', ['$http', function($http) { 
    var key = "a1f2d85f6babd3bf7afd83350bc5f2a6"; 
    return { 
     getWeatner: function(city) { 
      return $http.get('http://api.openweathermap.org/data/2.5/forecast?q=' + city + '&APPID=' + key + '&units=metric&cnt=5'); 
     } 
    } 
}]); 
+0

這幫了很大的忙! TY太多了!一旦完成,我會發布完成。 –

+0

很高興聽到你,請接受答案 – Gaurav

0

增加參數的回調,回調:JSON_CALLBACK

 
$http.jsonp("http://api.openweathermap.org/data/2.5/forecast?q='+city+'&APPID='+key+'&units=metric&cnt=5&callback=JSON_CALLBACK").success(function(data){ ... }); 
+0

一般API都支持jsonp,可以自己嘗試增加參數callback = JSON_CALLBACK –