如何在视图中访问角JS自定义过滤器JSON数据

时间:2022-12-09 19:45:19

I'm developing multi language support Angular JS project. I want to translate label names into a specific language (Label names - search sites, visit site. It is already have values). For this I'm not using Angular JS translate. I'm gonna write a new custom filter. ( What I planned is to have label name values in different languages in a seperate json file.)

我正在开发多语言支持角JS项目。我想把标签名称翻译成一种特定的语言(标签名称-搜索网站,访问网站。它已经有了价值。对于这个,我不使用角度JS平移。我要写一个新的自定义过滤器。(我所计划的是在一个seperate json文件中使用不同语言的标签名值。)

App Filter

应用过滤器

app.filter('langTrans', function() {
//Instead of reading values, I only added demo values to test.
var data ={"searchsites":"recherche ", "visitsite":"voir "}

return function(data) {
    //custom filter translation logic goes here

    return "//value goes here ";

}  }); 

In my view , I have called filter using a pipe. But instead of retriving all values , I only need to return the value of specific element (Ex: for first button I only need to retrieve search site translated value)

在我看来,我使用管道调用了filter。但是我不需要检索所有的值,我只需要返回特定元素的值(例如:对于第一个按钮,我只需要检索搜索站点翻译的值)

 <li>
  <md-button ng-href="#!/search">{{searchsites | langTrans}}</md-button>
</li>
<li>
  <md-button ng-href="#!/visit">{{ visitsite | langTrans }}</md-button>
</li>

1 个解决方案

#1


2  

angular.module('app', []).filter('langTrans', function() {  
  var translate = [{
      'Language 1': {
        'searchsites': 'Job Search', 
        'visitsites': 'View Jobs',
      }
    },
    {
      'Language 2': {
        'searchsites': 'Recherche d emploi',
        'visitsites': 'Voir les offres',
      }
    },
    {
      'Language 3': {
        'searchsites': 'Пошук роботи',
        'visitsites': 'Переглянути роботу',
      }
    }
  ]

  return function(input, language) {
    return translate.filter(function(x){ return !!x[language]; })[0][language][input];
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app'>
  {{'searchsites' | langTrans : 'Language 3'}}
</div>

#1


2  

angular.module('app', []).filter('langTrans', function() {  
  var translate = [{
      'Language 1': {
        'searchsites': 'Job Search', 
        'visitsites': 'View Jobs',
      }
    },
    {
      'Language 2': {
        'searchsites': 'Recherche d emploi',
        'visitsites': 'Voir les offres',
      }
    },
    {
      'Language 3': {
        'searchsites': 'Пошук роботи',
        'visitsites': 'Переглянути роботу',
      }
    }
  ]

  return function(input, language) {
    return translate.filter(function(x){ return !!x[language]; })[0][language][input];
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app'>
  {{'searchsites' | langTrans : 'Language 3'}}
</div>