angularjs – 如何删除控制器之间的重复共享功能

我需要在控制器之间使用i18n转换功能.

因此每个控制器都应该有getCityName和getCountryName来将其转换为正确的lang.

我尝试使用Angular服务来减少重复.

如您所见,我仍然需要分别在两个控制器中定义这些功能.

在我的情况下,是否可以删除控制器中定义函数的重复?

谢谢

Departure.html

  <div  ng-repeat="departure in departures_lst">
    <div class="panel-title">
      <h5>{{getCountryName(departure.country)}}</h5>
    </div>
            <li  ng-repeat="city in departure.cities">
              <a ng-click="get_destinations(city)">
                {{getCityName(city)}}
              </a>
           </li>
  </div>

Arrival.html

  <div  ng-repeat="arrive in arrives_lst">
    <div class="panel-title">
      <h5>{{getCountryName(arrive.country)}}</h5>
    </div>
            <li  ng-repeat="city in arrive.cities">
              <a ng-click="get_destinations(city)">
                {{getCityName(city)}}
              </a>
           </li>
  </div>

角度js

App.service('I18nService', function () {
    this.getCountryName = function (country_name) {
      return I18n.t("country." + country_name) + country_name
    }
    this.getCityName = function (city_name) {
      return I18n.t("city." + city_name) + city_name
    }
});

App.controller("departures_ctrl", function($scope, I18nService, $location, $http) {
    $scope.getCountryName = function(country_name){
      return I18nService.getCountryName(country_name);
    }
    $scope.getCityName = function(city_name){
      return I18nService.getCityName(city_name);
    }
});

App.controller("arrivals_ctrl",  function($scope, $route, I18nService, $routeParams, $http, $window, $location) {
    $scope.getCountryName = function(country_name){
      return I18nService.getCountryName(country_name);
    }
    $scope.getCityName = function(city_name){
      return I18nService.getCityName(city_name);
    }


});

最佳答案 避免重复的一种方法是向服务功能添加参数.

你可以写这样的东西:

app.controller('FooCtrl', function($scope, TranslationService){

  $scope.getName = function(name, flag){
   TranslationService.getName(name,flag); 
  }

});

app.controller('BarCtrl', function($scope, TranslationService){

  $scope.getName = function(name, flag){
   TranslationService.getName(name,flag); 
  }

});

app.factory('TranslationService', function(){

  return {
    getName: function(name,flag){
      if(flag == 'city'){
          //...
      } 
      else{
        //...  
      }
    }
  }
})

在HTML视图中,您可以使用:

<div ng-app="myApp" ng-controller="FooCtrl">

  <p>{{getName(obj.city, 'city')}}</p>

</div>

如果你想避免在两个控制器中声明两次getName函数,你可以将函数分配给$rootScope但是IMO它不是一个理想的解决方案,因为它可以使代码的可读性降低.

点赞