2017-04-07 96 views
0

我想根据用户输入显示任何位置的天气。为此,我创建了一个将任何位置作为输入的输入字段。对于我已经使用将ng模型值绑定到http参数

NG-模型

指令绑定用户输入,并将其放置在$ HTTP参数字段。

该应用本来应该根据用户输入显示天气。如果有人能够查看我的代码并告诉我我做错了什么,我将不胜感激。

的html代码:

<!DOCTYPE html> 
<html> 
<script data-require="[email protected]" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script> 
<script src="app.js"></script> 
<head> 
    <meta charset="utf-8"> 
    <title>Angular JS</title> 
</head> 
<body ng-app="jsbin"> 
    <div ng-controller="DemoCtrl as vm"> 
    <form> 
    Location: <input type="text" ng-model="vm.location" value="Paris"> 
    <button type="button" ng-click=submit()>Submit</button> 
    </form> 
    <h1>{{ vm.data| json}}</h1> 

    </div> 

</body> 

</html> 

app.js:

var app = angular.module('jsbin', []); 

app.controller('DemoCtrl', function($http) { 

    var vm = this; 


    $scope.submit = function(){ 

    var URL = 'https://api.apixu.com/v1/current.json'; 
    var request = { 
     method: 'GET', 
     url: URL, 
     params: { 
     q: vm.location, 
     mode:'json', 
     cnt:'7', 
     units:'imperial', 
     key:'1a17370dc8e34f09946231209170404' 
     } 
    }; 

    $http(request) 
     .then(function(response) { 
     vm.data = response.data; 


     }). 
     catch(function(response) { 
     vm.data = response.data; 

     }); 
    }; 

}); 

回答

1

如果控制器进行实例化 “controllerAs” 语法,不要用$scope,使用this上下文。

在模板:

<div ng-controller="DemoCtrl as vm"> 
    <form> 
    <!-- WRONG 
    Location: <input type="text" ng-model="location" value="Paris"> 
    <button type="button" ng-click=submit()>Submit</button> 
    </form> 
    --> 
    <!-- RIGHT --> 
    Location: <input type="text" ng-model="vm.location" value="Paris"> 
    <button type="button" ng-click=vm.submit()>Submit</button> 
    </form> 

JS:

var vm = this; 
    //vm.location = location; 

    //$scope.submit = function(){ 
    vm.submit = function(){ 

    var URL = 'https://api.apixu.com/v1/current.json'; 
    var request = { 
     method: 'GET', 
     url: URL, 
     params: { 
     //q:'vm.location', 
     //USE variable 
     q: vm.location, 
     mode:'json', 
     cnt:'7', 
     units:'imperial', 
     key:'1a17370dc8e34f09946231209170404' 
     } 
    }; 

你能解释一下为什么是vm.location不仅location在NG-模型的指令?

当控制器与“controllerAs”语法实例化,$compile service结合控制器的this上下文具有指定名称的$scope对象的属性。要引用控制器this上下文的属性,模板应该使用在“controllerAs”绑定中指定的名称前缀这些属性名称。

AngularJS团队建议遵循always have a '.' in your ng-models —观看3分钟的“最佳做法”。 Misko用ng-switch演示原始绑定问题。

欲了解更多信息,请参阅AngularJS Wiki - Understanding Scopes.

+0

非常感谢@georgeawg。你能解释为什么它是“vm.location”而不是ng-model指令中的“location”? – Ufomammut