Utilizing AngularJS to implement a weather API search function for cities with the added functionality of

When using the code with the openweather api data, I can display low and high temperatures perfectly by declaring the city value in the input field (ex: value ="houston").

However, I want to create a function that captures the value I enter and displays the data when I press the enter key.

This way, I can view the data of any city I choose. Below is my code, which works fine if I don't include the enterkey function inside ng-keydown and manually declare a value instead. The issue might be the way I implemented the enterkey function in the JavaScript file.

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

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

    var ctrl = this;

    var URL = 'http://api.openweathermap.org/data/2.5/forecast/daily';
    var city = document.getElementById("search_box").value;
    var request = {
        method: 'GET',
        url: URL,
        params: {
            q: city,
            mode: 'json',
            units: 'imperial',
            cnt: '7',
            appid: 'd20b7e069e7858118979c0ed0b36f8b5'
        }
    }

    function enterkey() {
        var enterk = event.keyCode || event.which;

        if (enterk == 13) {

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

                    console.log(ctrl.data);
                })

        }
    }
})
   

<!DOCTYPE html>

<html>
<head>
    <link rel="stylesheet" type="text/css" href="../css/weatherangu.css">
    <meta charset="utf-8">
    <title>Angular JS</title>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js"></script>

</head>
<body ng-app="myapp">


    <div id="content" ng-controller="DemoCtrl as ctrl">

        <img id="w_pic" src="../images/7day.png">
        <input type="text" id="search_box" placeholder="Enter City Name Here.." ng-keydown="enterkey()">

        <div id="weather_data">
           <h1 class="zero">{{ ctrl.data.list[0].temp.max| json }}</h1><br>
           <h1 class="zero">{{ ctrl.data.list[0].temp.min| json }}</h1>

          <h1 class="one">{{ ctrl.data.list[1].temp.max| json }}</h1><br>
          <h1 class="one">{{ ctrl.data.list[1].temp.min| json }}</h1>

          <h1 class="two">{{ ctrl.data.list[2].temp.max| json }}</h1><br>
          <h1 class="two">{{ ctrl.data.list[2].temp.min| json }}</h1>

          <h1 class="three">{{ ctrl.data.list[3].temp.max| json }}</h1><br>
          <h1 class="three">{{ ctrl.data.list[3].temp.min| json }}</h1>

          <h1 class="four">{{ ctrl.data.list[4].temp.max| json }}</h1><br>
          <h1 class="four">{{ ctrl.data.list[4].temp.min| json }}</h1>

          <h1 class="five">{{ ctrl.data.list[5].temp.max| json }}</h1><br>
          <h1 class="five">{{ ctrl.data.list[5].temp.min| json }}</h1>

          <h1 class="six">{{ ctrl.data.list[6].temp.max| json }}</h1><br>
          <h1 class="six">{{ ctrl.data.list[6].temp.min| json }}</h1>

                  </div>
    </div>
    <script src="../js/weatherangu.js"></script>

</body>
</html>

Answer №1

To utilize the enter key, simply place your input within a form that contains a submit button. Utilize ng-submit to display information when the enter key is pressed. Remember to attach the functions called from the view to the $scope in Angular. Avoid using DOM functions in controllers by utilizing ng-model instead.

HTML

<form action="" method="get" ng-submit="submitForm()">
  <input ng-model="cityName" type="text" id="search_box" placeholder="Enter City Name Here..">
  <input type="submit" style="display:none"/>
</form>

JS

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

    var ctrl = this;

    var URL = 'http://api.openweathermap.org...';
    var request = {
        method: 'GET',
        url: URL,
        params: {
            //use ng-model instead of getElementById
            q: ctrl.cityName, 
            mode: 'json',
            ...
        }
    }

    ctrl.submitForm = function() {
        $http(request)
            .then(function (response) {
                ctrl.data = response.data;
                console.log(ctrl.data);
            })
    }
})

Although untested, this should give you a good starting point.

Answer №2

After receiving input from members, I successfully linked the input value to the city value using ng-model, enabling two-way data-binding. To dynamically update the data as I type in the city name, I had to manually implement $watch to monitor input changes and trigger the function accordingly. If anyone knows of a more efficient or recommended approach for achieving this, please share your insights.

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

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

    var ctrl = this;

    var URL = 'http://api.openweathermap.org/data/2.5/forecast/daily';
    
    $scope.request = {
        method: 'GET',
        url: URL,
        params: {
            q: 'london',
            mode: 'json',
            units: 'imperial',
            cnt: '7',
            appid: 'd20b7e069e7858118979c0ed0b36f8b5'
        }
    }

function test() {
    $http($scope.request)
        .then(function (response) {
            ctrl.data = response.data;
            console.log(ctrl.data);
        })
}
test();

$scope.$watch('request.params.q',function () {
    test();
})

})
<!--<!DOCTYPE html>
<html >
<head>
<link rel="stylesheet" type="text/css" href="../css/weatherangu.css">

  <title></title>
</head>
<body ng-app="wapp">
  



<input type="text" id="searchbox" placeholder="Type City Name Here.." onkeydown="enterkey()" >

<div id="posterdiv" ng-controller = "ctrl as vm">

<p> {{vm.data | json}}</p>

</div>


 <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js"></script>

<script src = "../JavaScript/weatherangu.js"></script>

</body>
</html>-->

<!DOCTYPE html>

<html>
<head>
  <link rel="stylesheet" type="text/css" href="../css/weatherangu.css">
  <meta charset="utf-8">
  <title>Angular JS</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>

</head>
<body ng-app="myapp">

  
  <div id="content" ng-controller="DemoCtrl as ctrl">

    <img id="w_pic" src="../images/7day.png">


   
    <input  type="text"   ng-model="request.params.q" id="search_box" placeholder="Enter City Name Here..">


    <div id="weather_data">
{{
       <h1 class="zero">{{ ctrl.data.list[0].temp.max| json }}</h1><br>
       <h1 class="zero">{{ ctrl.data.list[0].temp.min| json }}</h1>

      <h1 class="one">{{ ctrl.data.list[1].temp.max| json }}</h1><br>
      <h1 class="one">{{ ctrl.data.list[1].temp.min| json }}</h1>

      <h1 class="two">{{ ctrl.data.list[2].temp.max| json }}</h1><br>
      <h1 class="two">{{ ctrl.data.list[2].temp.min| json }}</h1>

      <h1 class="three">{{ ctrl.data.list[3].temp.max| json }}</h1><br>
      <h1 class="three">{{ ctrl.data.list[3].temp.min| json }}</h1>

      <h1 class="four">{{ ctrl.data.list[4].temp.max| json }}</h1><br>
      <h1 class="four">{{ ctrl.data.list[4].temp.min| json }}</h1>

      <h1 class="five">{{ ctrl.data.list[5].temp.max| json }}</h1><br>
      <h1 class="five">{{ ctrl.data.list[5].temp.min| json }}</h1>

      <h1 class="six">{{ ctrl.data.list[6].temp.max| json }}</h1><br>
      <h1 class="six">{{ ctrl.data.list[6].temp.min| json }}</h1>
}}
     </div>
  </div>

  <script src = "../js/weatherangu.js"></script>

</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a new JSON property by incorporating the value of an existing property

I have a file containing JSON-serialized data structured as shown below: { "name":"Store", "children":[ { "name":"Store 1", "children":[ { "name":"collection 1", ...

Steering clear of repeating evaluations and dynamically unloading objects requested with `require` is important

I'm currently delving into the intricacies of the nodejs module system. Among the resources I've come across so far are: https://nodejs.org/api/modules.html These readings have shed light on a few aspects, but I still have some lingering ques ...

What is the best way to implement react-router following the detection of an error using an error boundary?

In my React application built with create-react-app, I have implemented react-router for navigating between different components. Recently, I delved into error handling and came across error boundaries. My goal is to display the main structure of the appli ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...

Having trouble converting a JSON array into a JavaScript array upon creation

I have encountered this question multiple times before and despite trying various solutions, I have not been able to find success. Summary: My goal is to retrieve the array from the classes.json file and then assign the data in the variable classes from d ...

Having trouble with implementing Auth0 example in my Vue.js project, I keep getting the error "_vm.login is not a function(...)"

As a newcomer to both VUE and Auth0, I suspect that there may be some logical errors in my code causing this issue. It seems like something more experienced VUE developer would easily identify. When I click the "Login" button, I'm encountering an err ...

Discover the technique of accessing HTML/CSS toggle switch value in Golang

I am attempting to incorporate a toggle switch into my webpage. I followed this specific tutorial for guidance: w3schools.com Currently, I have set up my HTML file with a button and the toggle switch. Additionally, I configured my web server in Go to lis ...

confirm validity prior to executing controller logic

Looking to develop an Express REST API and in need of validating request params and the request body. The router file manages all routes. When accessing localhost:3000/users, the router would redirect to app.use('/users', require(`./routes/user ...

Can you conceal all content enclosed by two h2 tags?

Here is an example HTML snippet: <h2>Headline 1</h2> <p>Lorem ipsum bla bla</p> <p>Lorem ipsum bla bla</p> <p>Lorem ipsum bla bla</p> <h2>Headline 2</h2> <p>Lorem ipsum bla bla</p> ...

Is it beneficial to utilize components in order to streamline lengthy HTML code, regardless of whether the components do not repeat and do not require any props (such as in Vue or any other JavaScript library

In the Vue.js team project I am currently involved in, I have structured my code in the view as follows: component01 component02 ... There are more than 10 components in total. Each component represents a section of the landing page, consisting mostl ...

What is the procedure for verifying the type of an element using chai?

Is there a way to determine if an element is either an "a" tag or a "div" tag? I've tried the following code, but it's not working as expected: it('has no link if required', () => { const wrapper = shallow(<AssetOverlay a ...

The feature in AngularJs where ng-options (key, value) is used with ng-model="selected" is not functioning properly

Here is the HTML code I am working with: <select ng-options="value.name for (key, value) in countries track by key" ng-model="selected" > </select> This is the specific object I am trying to manipulate: $scope.countries = { "AFG":{"name" ...

Show data based on the chosen destination

Recently, I've been working on creating a simple printer manager to monitor the status of all my printers. Although I have successfully displayed all the data, I'm facing an issue while trying to organize it by location. The error message I keep ...

Text that changes within a set-sized box

I'm working with a fixed-size div that contains dynamically generated text. Is there an easy method using DOJO or plain Javascript to truncate the text before the end of the div and add "..."? How can I accomplish this regardless of the font size bein ...

A warning message has been triggered: 'Script Alert Error - Object

I've been putting in hours on a SUP project that requires some tweaking and I keep running into the issue Script Alert Error: Object expected The code I've added is: $('#bottomOfStart_ScreenForm').before('<div style="display: ...

Display element on the webpage upon clicking an event

I have a simple project in mind where I want to create an application that consists of a textArea component and a button. When the button is clicked, a function will take the user input and generate an object with each word and its frequency count. The ma ...

Encountering a JS error that states: "Uncaught SyntaxError: missing ) after argument list" when running the following code

I keep encountering the error message: "Uncaught SyntaxError: missing ) after argument list" when I try to call the delete function within the createHtmlview function. console.log("Delete Item is being called") } ...

Trouble communicating with child component in Vue 3.0 - no event received

I have a button component that acts as a child component <template> <div class="button-container"> <el-button @click="$emit('onClick')" type="primary">{{ text }}</el-button> </div&g ...

JavaScript - Troubleshooting issues with numbers displaying as NaN and objects being undefined

I am currently working on developing a comment generator for a specific program, and I have encountered an issue involving numbers. Initially, when performing the necessary calculations using the code block below, I received an object undefined error: tot ...

Error encountered: Attempting to access the 'length' property of an undefined variable in JSON data while using the $.each function

When I execute the following code snippet: var obj = $.parseJSON(json.responseText); $.each(obj.collection.response, function (i) { $.each(this.PRESENT_STUDENT, function (i, j) { $.each(j , function (i, j){ $( ...