javascript - How to take value from input and take it to AJAX request link? -


so have done ajax request angularjs:

http://jsfiddle.net/c0lkja0h/1/

when use link example $http.get('http://api.wunderground.com/api/key/forecast/geolookup/conditions/q/san_francisco.json') (without '+ city +' in link) works great. when add variable, add ng-model="city" , hit submit, says

city not defined

how can make take city name input , use in newajaxreq function when click "find weather" button ? cool default link static link (when person first visited site), , after city taken input if user wants. thanks!

there couple of things wrong approach.

  1. don't name controller. should anonymous function take parameters modules want inject, such .controller(function($http){ //do }); or .controller(['$http',function($http){ //do }]) avoid losing reference variables when minify js files.
  2. inside controller, define function want takes parameter city, such $scope.sendajax = function(city){ //do }. in view gonna call function argument need ng-submit="sendajax(city)"
  3. avoid using scope. great book angularjs:up , running, shyam seshadri , brad green:

if used angularjs prior 1.2, might have expected $scope variable injected controller, , variables hellomsg , goodbyemsg set on it. in angularjs 1.2 , later, there new syntax, controlleras syntax, allows define variables on controller instance using this keyword, , refer them through controller html.

the advantage of on earlier syntax makes explicit in html variable or function provided controller , instance of controller. complicated, nested ui, don’t need play game of “where’s waldo?” find variables in codebase. becomes obvious be‐ cause controller instance present in html.

the alternative in view use controller syntax: "ng-controller="weathercontroller weather", , refer alias when need access weather controller scope, such ng-submit="weather.sendajax()".

in controller, assign function this, in this.sendajax = function(){ \\do }. practice assign this variable, since this can overriden. in first line of controller can var self=this , refer controller self point on, in self.sendajax = function(){ \\do }


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -