【问题标题】:AngularJS, How to get the value from input and place it in a factory?AngularJS,如何从输入中获取值并将其放入工厂?
【发布时间】:2015-10-17 00:22:10
【问题描述】:

我正在尝试像这个人一样做同样的事情:How to send data from input to service?,并且我复制/粘贴了每个提供的解决方案,但我无法让它发挥作用。 这是我的起点,当我编写这样的代码时,它可以正常工作:

var town="London";
//factory
scotchApp.factory('forecastBG', ['$http', function($http) { 
        return $http.get('http://api.openweathermap.org/data/2.5/find?q=' + town + '&units=metric&appid=bd82977b86bf27fb59a04b61b657fb6f') 
            .success(function(data) { 
              return data; 
            }) 
            .error(function(err) { 
              return err; 
      }); 
}]);


    //controller
scotchApp.controller('beograd', ['$scope', 'forecastBG', function($scope, forecastBG) {
  forecastBG.success(function(data) {
    $scope.fiveDay = data;
  });
}]);


//view

    <div class="forecast">          
        <div ng-controller="beograd" class="first">
            <p></p> 
            <p style="font-size: 130%"> City </p>
            <p style="font-size: 130%">{{ fiveDay['list'][0].main.temp }}&degC</p>
            <p> Wind: {{ fiveDay['list'][0].wind.speed }} m/s</p>
            <p> Pressure: {{ fiveDay['list'][0].main.pressure }}hpa</p>
            <p> Humidity: {{ fiveDay['list'][0].main.humidity }}%</p>
            <p style="font-size: 90%"> Min. temp.: {{ fiveDay['list'][0].main.temp_min }}&degC</p>
            <p style="font-size: 90%"> Max. temp.: {{ fiveDay['list'][0].main.temp_max }}&degC</p>
            <p style="font-size: 90%"> {{ fiveDay['list'][0]['weather'][0].description }}</p>
        </div>                      
    </div>

现在,我正在想办法从输入字段中获取值,将该值传递给 var town,然后单击一个按钮,使用新信息刷新视图。这个想法是让用户可以搜索和获取此 API 上可用的任何城市的信息。 请帮忙,我会努力完成这项工作,而且我对 Angular 很陌生。

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    几个部分 - 首先你需要让你的工厂返回一个以town 作为参数的可调用函数(也将使用.then 来返回一个承诺):

    scotchApp.factory('forecastBG', ['$http', function($http) { 
        return {
            getWeatherForTown: function(town) { 
                return $http.get('http://api.openweathermap.org/data/2.5/find?q=' + town + '&units=metric&appid=bd82977b86bf27fb59a04b61b657fb6f') 
                .then(function(result) { 
                    return result.data; 
                }) 
            }
        }
    }]);
    

    现在,创建一个控制器函数来处理您的点击事件并调用您的工厂:

    $scope.getWeather = function(town) {
        forecastBG.getWeatherForTown(town).then(function(data) {
            $scope.fiveDay = data;
        });
    }
    

    并更新视图以调用此方法并传入您的 input 模型:

    <input type="text" ng-model="townToSearchFor" />
    <button ng-click="getWeather(townToSearchFor)" ng-disabled="!townToSearchFor">Get Weather!</button>
    

    【讨论】:

    • 先生,言语无法表达我对这个答案的感激之情。
    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    相关资源
    最近更新 更多