在控制器中保持代码干燥的角度方式

时间:2016-09-14 13:54:48

标签: javascript angularjs ionic-framework

所以我正在构建一个Ionic应用程序只是为了熟悉它,这是我第一次使用Angular而且我还没有完全采用Angular的思维方式。

我有两个服务,一个返回一个位置,另一个返回该位置的天气。我将我的数据组织在服务中并发送到控制器,我在控制器中使用控制器中的服务功能为视图中使用的每个数据点设置$ scope变量。我想在控制器中集成一个“拉动刷新”功能,现在我只是复制了最初在控制器中的代码并将其包装在ion.Refresher指令中。保持此代码DRY的最佳方法是什么。

谢谢!

services.js

angular.module('weather.services', [])

.service('getLocation', function($http){
  this.getData = function(lat, long) {
    var promise = $http({
      method: 'GET',
      url: 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + long
    }).success(function(data) {
      data.location = data.results[3].address_components[0].long_name;
      return data.location;
  });
  return promise;
 }
})

.service('getWeather', function($http){
  this.getData = function(lat, long) {
    var promise = $http({
        method: 'jsonp',
        url:  'https://api.forecast.io/forecast/api-key/' + lat + ',' + long + '?callback=JSON_CALLBACK'
    }).success(function(data) {
      data.currentTemperature = parseInt(data.currently.temperature);
      data.summary = data.currently.summary;
      data.icon = data.currently.icon;

      var timestamp = moment.unix(data.currently.time);
      var formattedDate = moment(timestamp, "YYYY-MM-DD HH:mm:ss")
      data.todaysDate = formattedDate.format('dddd Do MMMM');

      var daily_data = data.daily.data;
      var days = []
      angular.forEach(daily_data, function(value, key) {
        this.push(value);
      }, days);
      data.dailyWeather = days;

      // hourly weather for side scroll
      var hourly_data = data.hourly.data;
      var hours = []
      angular.forEach(hourly_data, function(value, key) {
       this.push(value);
      }, hours);
      data.hourlyWeather = hours;

      return data;
    });
    return promise;
   }
 })

controller.js

angular.module('weather.controllers', [])

.controller('HomeCtrl', function($scope, $http, getLocation, getWeather, $cordovaGeolocation) {

  $cordovaGeolocation
    .getCurrentPosition()
    .then(function (data) {
      $scope.latitude = data.coords.latitude;
      $scope.longitude = data.coords.longitude;

      // Gets location and city you are in
      getLocation.getData($scope.latitude, $scope.longitude).then(function(data){
        $scope.location = data.data.location;
      })

      // Gets the weather data for the city you are in
      getWeather.getData($scope.latitude, $scope.longitude).then(function(weather){
        $scope.weather = weather.data;
        $scope.today = weather.data.todaysDate;
        $scope.weather.currentTemp = weather.data.currentTemperature;
        $scope.weather.summary = weather.data.summary;
        $scope.weather.icon = weather.data.icon;
        $scope.weather.daily = weather.data.dailyWeather;
        $scope.weather.hourly = weather.data.hourlyWeather;
      })
    }, function(err) {
      console.debug(err);
    });

    // see the repeated code
    $scope.doRefresh = function() {
      console.log('currently refreshing data')
      $cordovaGeolocation
        .getCurrentPosition()
        .then(function (data) {
          $scope.latitude = data.coords.latitude;
          $scope.longitude = data.coords.longitude;

          // Gets location and city you are in
          getLocation.getData($scope.latitude, $scope.longitude).then(function(data){
            $scope.location = data.data.location;
          })

          // Gets the weather data for the city you are in
          getWeather.getData($scope.latitude, $scope.longitude).then(function(weather){
            $scope.weather = weather.data;
            $scope.today = weather.data.todaysDate;
            $scope.weather.currentTemp = weather.data.currentTemperature;
            $scope.weather.summary = weather.data.summary;
            $scope.weather.icon = weather.data.icon;
            $scope.weather.daily = weather.data.dailyWeather;
            $scope.weather.hourly = weather.data.hourlyWeather;
          })

          $scope.$broadcast('scroll.refreshComplete');
        }, function(err) {
          console.debug(err);
        });
    }
});

1 个答案:

答案 0 :(得分:1)

您可以这样做以保持代码干燥,与其他代码相同:

.controller('HomeCtrl', function($scope, $http, getLocation, getWeather, $cordovaGeolocation) {

  $scope.loadData = function(isRefreshing) {
     ...// your code to load location and weather data here.
     //// 
     if (isRefreshing) {
        // broadcast your event
     }
  }

  $scope.loadData(); // load data for the first time
  $scope.doRefresh = function() {
     $scope.loadData(true); // load data on refreshing
  }