如何通过变量值?

时间:2017-02-21 09:14:59

标签: angularjs ionic-framework

对于那些可能更熟悉在AngularJs / Ionic 2中编写变量的人,我恳请你能否为我提供以下所需的解决方案:

在我的app.components文件中,我在下面设置了sidemenu项目。我已将变量translatedPageA添加到每一行:

appPages: PageInterface[] = [
  { title: translatedPageA, component: TabsPage, tabComponent: PageAPage },
  { title: translatedPageB, component: TabsPage, tabComponent: PageBPage },
  { title: translatedPageC, component: TabsPage, tabComponent: PageCPage },
  { title: translatedPageD, component: TabsPage, tabComponent: PageDPage }

];  

我需要将一些变量值传递给它:

{{'translatedPageA' | translate }} 

正如您所看到的,因为这包含在表达式中是我无法插入另一个表达式的原因。所以解决方案是先通过一个变量。如何创建此变量以及在何处插入此变量?

我试过了:

var translatedPageA: {{'HOME' | translate }};

1 个答案:

答案 0 :(得分:0)

您可以使用$translate.instant()。这个AngularJS translation助手将允许您直接在控制器内翻译标记。

myApp.controller('MyCtrl', function ($scope, $translate) {

    //translate inside controller with instant
    var PageInterface = [
        { title: $translate.instant('HOME'), component: TabsPage, tabComponent: PageAPage },
        { title: $translate.instant('SIDEB'), component: TabsPage, tabComponent: PageBPage },
        { title: $translate.instant('SIDEC'), component: TabsPage, tabComponent: PageCPage },
        { title: $translate.instant('SIDED'), component: TabsPage, tabComponent: PageDPage }
    ];  
});

另一种方法是将标题值直接解析到您的视图中。这可以像这样做:

Demo fiddle

视图

<div ng-repeat="interfaceItem in pageInterface">
  {{ interfaceItem.title | translate}}
</div>

AngularJS控制器

myApp.controller('MyCtrl', function ($scope, $translate) {

    //translate inside controller with instant
    $scope.pageInterface = [
        { title: 'HOME' , component: TabsPage, tabComponent: PageAPage },
        { title: 'SIDEB', component: TabsPage, tabComponent: PageBPage },
        { title: 'SIDEC', component: TabsPage, tabComponent: PageCPage },
        { title: 'SIDED', component: TabsPage, tabComponent: PageDPage }
    ];  
});