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",$route,$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',TranslationService){

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

});

app.controller('BarCtrl',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它不是一个理想的解决方案,因为它可以使代码的可读性降低.

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...