The controller assignment is failing to transfer to the service

I am currently facing an issue with my assignment in the controller where $scope.getForecastByLocation is not being passed through properly. The problem lies in the fact that the variable city is hardcoded to a random city like "Berkeley", and this city value is then passed to the Data factory. However, the intention is for the user to input a new city, which should then be sent as a parameter to the Data factory.

Despite my efforts of using console.logs, I can see that the button is functioning correctly. However, when calling Data.getApps($scope.inputcity);, it does not work as expected, resulting in the city always being set as "Berkeley".

If anyone can identify why I'm unable to send a new city parameter to the Data factory, I would greatly appreciate it! Thank you!

In my HTML file:

 <input ng-model="city">
  </md-input-container>
  <md-button class="md-raised" ng-click="getForecastByLocation(city)">SUBMIT</md-button>

In my controller.js file:

var app = angular.module('weatherApp.controllers', [])

    var city = 'Berkeley';

    app.controller('weatherCtrl', ['$scope','Data',

        function($scope, Data) {
        $scope.getForecastByLocation = function(city) {
                $scope.inputcity = city;
                console.log($scope.inputcity);
                Data.getApps($scope.inputcity).then(function(data){
                    $scope.data = data;
                    $scope.name = data.name;
                    console.log($scope.data); //object shows "Berkeley"
                    console.log($scope.name);
                 });//initiate Data.getApps by passing in a new city
         }
        Data.getApps(city).then(function(data) {
          $scope.data = data;

          var vm = $scope;

          vm.description = data.weather[0].description;
          vm.speed = (2.237 * data.wind.speed).toFixed(1) + " mph";
          vm.name = data.name;
          vm.humidity = data.main.humidity + " %";
          vm.temp = data.main.temp;
          vm.fTemp = (vm.temp * (9 / 5) - 459.67).toFixed(1) + " °F";

        },function(res) {
            if(res.status === 500) {
                // server error, alert user somehow
            } else { 
                // probably deal with these errors differently
            }
        }

        ); // end of function

    }])//end of controller

In my service.js file:

app.factory('Data', function($http, $q) {

    var data = [],
       lastRequestFailed = true,
       promise;
   return {
      getApps: function(city) {
         if(!promise || lastRequestFailed) {
            // $http returns a promise, so we don't need to create one with $q

            promise = $http.get('http://api.openweathermap.org/data/2.5/weather?',{
              params: {
                q: city,
              }
            })
            .then(function(res) {
                lastRequestFailed = false;
                data = res.data;
                return data;
            }, function(res) {
                return $q.reject(res);
            });
         }
         return promise;
      }
   }
});

A recent edit has been made to my controller code based on suggestions from others. Here is what the updated code looks like:

app.controller('weatherCtrl', ['$scope','Data',

    function($scope, Data) {
$scope.city = 'Berkeley';

$scope.getForecastByLocation = function() {
                console.log($scope.city); //making sure I can read the input
                console.log('this is your input ' + $scope.city);
                Data.getApps($scope.city).then(function(data){
                console.log('this is your output ' + $scope.city); //should say "This is your output "tracy", but it still reads at "Berkeley"

                    $scope.data = data;
                    $scope.name = data.name;
                    console.log($scope.data); //object shows "Berkeley"
                    console.log($scope.name);
                 });//initiate Data.getApps by passing in a new city
         }

https://i.sstatic.net/fR917.png

Answer №1

var app = angular.module('weatherApp.controllers', [])

    var city = 'San Francisco'; 

    app.controller('weatherCtrl', ['$scope','Data',

        function($scope, Data) {
        $scope.getForecastByLocation = function() {
                $scope.inputcity = $scope.city;
                console.log($scope.inputcity);
                Data.getApps($scope.inputcity).then(function(data){
                    $scope.data = data;
                    $scope.name = data.name;
                    console.log($scope.data); //object shows "San Francisco"
                    console.log($scope.name);
                 });//initiate Data.getApps by passing in a new city
         }
        Data.getApps(city).then(function(data) {
          $scope.data = data;

          var vm = $scope;

          vm.description = data.weather[0].description;
          vm.speed = (2.237 * data.wind.speed).toFixed(1) + " mph";
          vm.name = data.name;
          vm.humidity = data.main.humidity + " %";
          vm.temp = data.main.temp;
          vm.fTemp = (vm.temp * (9 / 5) - 459.67).toFixed(1) + " °F";

        },function(res) {
            if(res.status === 500) {
                // server error, alert user somehow
            } else { 
                // probably deal with these errors differently
            }
        }

        ); // end of function

    }]);
    app.factory('Data', function($http, $q) {

    var data = [],
       lastRequestFailed = true,
       promise;
   return {
      getApps: function(city) {
         if(!promise || lastRequestFailed) {
            // $http returns a promise, so we don't need to create one with $q

            promise = $http.get('http://api.openweathermap.org/data/2.5/weather?',{
              params: {
                q: city,
              }
            })
            .then(function(res) {
                lastRequestFailed = false;
                data = res.data;
                promise = false; // reset the promise value.
                return data;
            }, function(res) {
                return $q.reject(res);
            });
         }
         return promise;
      }
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="weatherApp.controllers">
    <div ng-controller="weatherCtrl">
        <input ng-model="city">
        <md-button class="md-raised" ng-click="getForecastByLocation()">SUBMIT</md-button>
    </div>
</div>

Answer №2

It seems like your controller might be assigning the value of $scope.inputcity incorrectly to a static variable called var city = 'Berkeley' instead of using the function argument city. To prevent confusion, it's recommended to use unique variable names for both the function's scope and its arguments.

Instead of passing city as an argument in

ng-click="getForecastByLocation(city)"
, why not directly access $scope.city within your controller?

Your updated function could resemble the following:

$scope.getForecastByLocation = function() {
    console.log($scope.city);
    Data.getApps($scope.city).then(function(data){
        $scope.data = data;
        $scope.name = data.name;
        console.log($scope.data); //object shows "Berkeley"
        console.log($scope.name);
    });
}

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

Bringing in Vue from 'vue' allows for the incorporation of 'different' Vue to diverse documents

This issue involves the interaction between Webpack, ES6 import syntax, and Vue. Currently, I am working on a Vuex mutation that is responsible for adding a new key-value pair mykey: [] to an object within the state. To ensure reactivity, I need to use Vu ...

Dynamically binding image URLs in VUEJS

Below is the JSON data containing button names and their corresponding image URLs: buttonDetails= [ { "name": "button1", "images": [{ "url": "https://localhost:8080/asset/d304904a-1bbd-11e6-90b9-55ea1f18bb ...

How can I effectively transmit data using the AngularJs Sdk in the Loopback factory?

I am struggling with the following code snippet in my Angular factory: getPermissions: function(modelId){ var Pers = Permission.find({ filter : { where : { and : [ { user_id : $rootScope.userId ...

Utilize JavaScript/jQuery to check for upcoming deadlines in a SharePoint 2013 list

I need to check if an item is due based on its date. When a user creates an item with a date in the format MM/DD (e.g., 06/15), I want to determine if that date falls within the next 30 days, turning it red, within the next 60 days, turning it orange, or g ...

Unable to trigger @click event on nuxt-link component within Nuxt 3

As per a Nuxt 2 question on Stack Overflow, it was suggested that the following code should prevent nuxt-link from navigating to a new page: <nuxt-link :to="`/meet`" class="group font-normal" @click.native="event => event.pre ...

Can you help me understand how to create a JSON file using webpack?

My goal is to create a customized `manifest.json` file for Chrome extensions in a more efficient, programmatic manner. Utilizing npm for dependency management, I've noticed that the `package.json` shares key fields with the `manifest.json`, such as "n ...

What is the best way to send checkbox values to ActionResult in MVC5?

I am working on an MVC5 application and within my view, I have the following code snippet: <div class="form-group"> @Html.LabelFor(model => model.CategoryID, "Category", htmlAttributes: new { @class = "control-label col-md-3" }) <div c ...

What is the best way to use useCallback within loops?

I am currently exploring the concepts of memo and useCallback, and to better grasp them, I have created a simple example: import { memo, useCallback, useState } from "react"; import { Button, Text, TouchableOpacity, SafeAreaView } from "reac ...

Tips for isolating the month values from the res.body.results array of objects with the help of JS Array map()

Looking to adjust the custom code that I have which aims to extract months from a string using regex. It seems like I'm almost there but not quite hitting the mark. When checking the console log, I am getting "undefined" values for key/value pairs and ...

Angular 2: Enhancing Tables

I am looking to create a custom table using Angular 2. Here is the desired layout of the table: https://i.sstatic.net/6Mrtf.png I have a Component that provides me with data export class ResultsComponent implements OnInit { public items: any; ngO ...

Modules failing to load in the System JS framework

Encountering a puzzling issue with System JS while experimenting with Angular 2. Initially, everything runs smoothly, but at random times, System JS struggles to locate modules... An error message pops up: GET http://localhost:9000/angular2/platform/bro ...

The Map Function runs through each element of the array only one time

I'm new to JavaScript and experimenting with the map() function. However, I am only seeing one iteration in my case. The other elements of the array are not being displayed. Since this API generates random profiles, according to the response from the ...

Tips for accessing a component method in React from a WebSocket callback

Struggling with Javascript and React here. The goal is to update a component's state using push messages from a WebSocket. The issue lies in calling the function handlePushMessage from the WebSocket callback. Here's the code snippet: const Main ...

Is utilizing unregistered HTML elements for semantic purposes considered poor practice?

When it comes to styling and semantic purposes, I am considering using unregistered web components. This means utilizing tags like <t-card></t-card> without registering them with customElements.define. Surprisingly, the browser and stylesheets ...

Tips on eliminating the 'first', 'previous', 'next', and 'last' buttons in the twbs pagination plugin

I am searching for a straightforward pagination solution that only displays page numbers without control buttons like "first," "previous," "next," and "last." I have looked through the options available in twbs-pagination's github documentation and on ...

Unforeseen issues arise when using material ui's Select component in conjunction with 'redux-form'

I am encountering an issue with a 'redux form' that includes a Select component from the latest material-ui-next. import { TextField } from 'material-ui'; <Field name="name" component={TextField} select > <MenuIte ...

The swf file doesn't stretch to fit the window when the height is set to 100%

Struggling with creating a flash recorder controlled by JavaScript? Trying to get the flash to fill the browser window but disappearing when setting height or width to 100%? Where am I going wrong? <div id="flashrecorder"> <object wmode="trans ...

Issue with code displaying boxes according to selected radio checkboxes

I stumbled upon this Code Snippet, but for some reason, I can't seem to make it work on my website or even on a simple test page. I'm not sure what I'm overlooking? Check out the JS Fiddle: http://jsfiddle.net/technologrich/tT48f/4/ I&apos ...

The ng-repeat directive is failing to generate a list item within an unordered list

I can't seem to figure out what's wrong with my code. For some reason, cust.name and cust.city are not showing up on the page. Additionally, I'm having trouble understanding why the list items are not being generated as expected. <html& ...

Transferring data through Ajax communication

I am currently facing an issue while working on a project. I cannot seem to figure out what is wrong with my code. Below is the snippet of my code where I am having trouble with the Ajax url not being able to access the function ReceivedMessageByIndexNumbe ...