javascript - binding ng-model value into http parameter -
i trying show weather of location based on user input. have created input field takes location input. have used
ng-model
directive bind user input , place in $http parameter field.
the app supposed show weather based on user input. grateful if code , tell me did wrong.
html code:
<!doctype html> <html> <script data-require="angularjs@1.5.8" 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 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; }); }; });
if controller instantiated "controlleras" syntax, don't use $scope, use this context.
in template:
<div ng-controller="democtrl 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' } }; could explain why
vm.location, notlocationin ng-model directive?
when controllers instantiated "controlleras" syntax, $compile service binds this context of controller property of $scope object specified name. reference properties of controllers this context, template should prefix property names name specified in "controlleras" binding.
the angularjs team recommends following "best practice" of always have '.' in ng-models — watch 3 minutes worth. misko demonstrates primitive binding issue ng-switch.
for more information, see angularjs wiki - understanding scopes.
Comments
Post a Comment