2017-03-02 49 views
0

$ http.get('example.com/api/json/'+'input.value')in angularjs控制器函數並更新{{data}}根據輸入實時輸入值來自angularjs,用於ulj http.get

var id="de1cfb221f978cebde0db9adfb5da6b9"; 
 
var city ="London"; 
 

 
angular.module('moo', []) 
 
.controller('mooAngular', function($scope, $http) { 
 

 
    $http.get('http://api.openweathermap.org/data/2.5/weather?' + 
 
    'q=' +city + 
 

 
    \t '&appid=' + id 
 
    ). 
 
     then(function(response) { 
 
      $scope.myData = response.data 
 

 

 
     }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div class="container" ng-app="moo" ng-controller="mooAngular" ng-init=""> 
 
<p>T(K) ={{myData.main.temp}}&deg;</p> 
 
<input id="city" type="text" ng-change="city" name="city" placeholder="Enter name here" value=""> 
 
</div>

+1

歡迎堆棧溢出。你應該讓你的文章更加精確。你的問題是什麼?你的代碼的結果是什麼?期望的結果是什麼? – gus27

回答

0

如果我理解正確的,你想爲網址動態值,可以用 「$範圍」:

var id="de1cfb221f978cebde0db9adfb5da6b9"; 
var city ="London"; 

angular.module('moo', []) 
.controller('mooAngular', function($scope, $http) { 
    $scope.city = city; 
    $scope.$watch('city', function(){ 
     console.log($scope.city); 
    }); 

    $http.get('http://api.openweathermap.org/data/2.5/weather?' + 'q=' +$scope.city + '&appid=' + id 
    ).then(function(response) { 
     $scope.myData = response.data; 
    }); 
}); 

此外,您還可以更新如下:

<!DOCTYPE html> 
<html> 
    <head> 
    <link rel="stylesheet" href="style.css"> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
    <script src="script.js"></script> 
    </head> 
    <body ng-app="moo"> 
    <h1>Hello Plunker!</h1> 
    <div class="container" ng-controller="mooAngular"> 
     <p>T(K) ={{myData.main.temp}}&deg;</p> 
     <input id="city" type="text" ng-model="city" placeholder="Enter name here" > 
    </div> 
    </body> 
</html> 

這裏去工作plnkr:

https://plnkr.co/edit/uDG73ajQ0Ab9iPFIaIVU?p=preview

我用手錶控制器,只是爲了表明城市價值正在更新。您也可以在$ watch中自定義/移動您的$ http請求。

恕我直言,你應該使用下拉列表輸入城市名稱,因爲你可以直接點擊天氣服務器,否則你將不得不驗證城市名稱。

更新的摘要,以$表內GET請求:

var id="de1cfb221f978cebde0db9adfb5da6b9"; 
var city ="London"; 

angular.module('moo', []) 
.controller('mooAngular', function($scope, $http) { 
    $scope.city = city; 
    $scope.$watch('city', function(){ 
     console.log($scope.city); 
     $http.get('http://api.openweathermap.org/data/2.5/weather?' + 'q=' +$scope.city + '&appid=' + id) 
     .then(function(response) { 
      $scope.myData = response.data; 
     }); 
    }); 
}); 
+0

我已經這樣做了,當履行輸入時,數據不同步。 – Alex

+0

@Alex是否嘗試過更新後的代碼段? –