我需要在控制器之间使用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它不是一个理想的解决方案,因为它可以使代码的可读性降低.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。