ng-submit调用工厂函数后如何更新视图?

时间:2015-06-15 00:26:53

标签: javascript angularjs

$ scope.temp和$ scope.description在ng-submit调用$ scope.getWeather之前没有值。我可以在提交后记录值,但无法更新视图以显示它们。 $ scope.test证明我的视图只显示"这是一个默认值"而不是更新到"这是新值"当$ scope.getWeather被调用时。谢谢。

angular.module('forecastCtrl', ['weatherService'])
.controller('forecastController', function($http, $scope, Weather) {
    //var vm = this;

    $scope.test = 'This is a DEFAULT value';

    $scope.getWeather = function(postData) {

        Weather.get(postData)
            .success(function(data) {
                console.log(data);
                $scope.test = 'This is the NEW value';
                $scope.temp = data.query.results.channel.item.condition.temp;
                $scope.description = data.query.results.channel.item.condition.text;
            })
            .error(function(error) {
                console.log(error);
            });

        event.preventDefault();
    };

// THIS IS THE FORM
<form name="getWeatherForm" action="#" ng-submit="getWeather(postData)" class="small-10 large-6 small-centered large-centered columns">
    <div class="row collapse">
         <div class="small-9 columns">
             <input type="text" placeholder="Philadelphia, PA" ng-model="postData.city">
         </div>
         <div class="small-3 columns">
              <button type="submit" class="button postfix">Go</button>
         </div>
    </div> 
</form>


//THIS IS THE FACTORY
angular.module('weatherService', [])
.factory('Weather', function($http) {
    return {
        get: function(location) {
            location = location.city;
            location = location.replace(/\s/g, '');
            // do error handling
            return $http.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22'+location+'%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys');
        }
    }
});

// THE VIEW
<main id="content">
<div class="row">
    <div class="small-12 large-12 columns">
        <section class="wrapper">
            {{ test }}
            <h1>{{ forecast.temp }}</h1>
            <h2>{{ forecast.description }}</h2>
        </section>
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

代码正在运行,但是当没有提供城市或提供错误的城市时,repsonse没有假定的属性。所以也许使用ng-required,因为如果未设置postData.city,代码将失败

http://plnkr.co/edit/7F3EUMyAXtAlBR9CGWb0?p=preview

       .success(function(data) {
            console.log(data);
            $scope.test = 'This is the NEW value';
            $scope.temp = data.query.results.channel.item.condition.temp;