2014-02-24 35 views
1

我在這個項目中使用了angularjs,我想要做的就是在一個視圖中輸入一個郵政編碼,並在單擊提交時在下一個視圖中顯示生成的天氣。問題是$ scope.zipcode沒有使用新的郵政編碼進行更新。如果起始代碼留空,則console.log表示未定義,如果我在其中放置了某些內容,則結果顯示爲默認的zip,但不包含其他任何內容。請幫忙。謝謝。

好吧所以這裏是我的代碼

路由CONFIGS

/* routing configs */  

var weather1 = angular.module('weather1', ['ngRoute']); 

weather1.config(['$routeProvider', function($routeProvider){ 
$routeProvider 
    .when('/show',{ 
     templateUrl:'templates/showWeather.html', 
     controller: 'WeatherController'}) 
    .when('/default',{ 
     templateUrl:'templates/inputZip.html', 
     controller: 'WeatherController'}) 
    .when('/about',{ 
     templateUrl:'templates/about.html', 
     }) 

    .otherwise({ 
     redirectTo: '/default' 
    }); 
}]); 

控制器

/* cntrls */ 

weather1.controller('WeatherController', function($http, $scope, $location) { 
$scope.list = []; 
$scope.zipcode = ''; 
var zip = '99114'; 
var urlBase = 'http://api.wunderground.com/api/cf6c8139e5b43574/conditions/q/'; 
var call = '.json?callback=JSON_CALLBACK'; 
var request = urlBase.concat($scope.zipcode,call); 

$scope.submit = function(){ 
     if($scope.zipcode){ 
      $scope.list.push(this.zipcode); 
      $scope.zipcode=''; 
      $location.path('/show'); 
     } 
}; 
    $http.jsonp('http://api.wunderground.com/api/cf6c8139e5b43574/conditions/q/' + zip + '.json?callback=JSON_CALLBACK').success(function(data) { 
     $scope.weather = data.current_observation; 
    console.log($scope.weather); 
    }).error(function(data) { 
     console.log('fail'); 
    }); 
}); 

inputZip.html

<form ng-submit="submit()"> 
    <input type='text' name='zipcode' ng-model='zipcode' required> 
    <input type='submit' id='submit' value='Check weather' /> 
</form> 

showWeather.html

<font size='75'>{{weather.temp_f}}</font>F; {{weather.weather}} in {{weather.display_location.full}} <img src='{{weather.icon_url}}'> 
<a href='#/default'>Back</a> 

回答

0

我認爲當你做location.path('/show');時,你實際上正在創建一個新的控制器實例,即使它是同一個控制器。這就是爲什麼你失去了你的價值。您應該確保不要重新初始化控制器或使用服務在兩個控制器之間共享數據。

+0

你會如何建議不要重新初始化控制器?我會使用location.path以外的東西嗎? – user3348396

+0

實際上,我認爲使用服務來存儲控制器之間共享的數據/邏輯是最好的方法。這樣你可以不斷添加控制器,他們都可以訪問相同的數據。作爲一個經驗法則,大多數業務邏輯都應該服務於其中。我喜歡將控制器視爲將我的服務中的邏輯綁定到HTML視圖的粘合劑。 – NicolasMoise

+0

因此,製作兩個不同名稱的控制器,並將它們在服務中具有的任何邏輯相同。 – NicolasMoise