加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 16:55:57 所属栏目:安全 来源:网络整理
导读:我需要在控制器之间使用i18n转换功能. 因此每个控制器都应该有getCityName和getCountryName来将其转换为正确的lang. 我尝试使用Angular服务来减少重复. 如您所见,我仍然需要分别在两个控制器中定义这些功能. 在我的情况下,是否可以删除控制器中定义函数的重
我需要在控制器之间使用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它不是一个理想的解决方案,因为它可以使代码的可读性降低.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读