2017-04-07 67 views
2

我只是现在试图让我的挂钩nativescript使用javascript,有一个非常基本的问题:使用nativescript转换器

let costFormatter= { 
     toView(value){ 
      console.log('Got:' + value); 
      return '$' + value; 
     }, 
     toModel(value){ 
      console.log('Got:' + value); 
      return '$' + value; 
     } 
    }; 
    http.getJSON("<My API Call>").then(function (r){ 
     page.bindingContext = { 
      deals: r, 
      costFormatter:costFormatter 
     }; 
    }, function (e){ 
     //// Argument (e) is Error! 
     //console.log(e); 
    }); 

在上面的代码中,我定义了成本格式化我只是想添加一个$除了我的listview标签上每个销售价格的价格。要使用呈现列表视图进口:

<ListView id="SteamItems" items="{{ deals }}"> 
         <ListView.itemTemplate> 
          <GridLayout columns="*, *, 50, 50" rows="50, 50, auto, *"> 
           <Image src="{{ thumb }}" row="0" col="0" cssClass="thumb"/> 
           <Label text="{{ title }}" key="1" row="0" col="1" cssClass="title"/> 
           <Label text="{{ normalPrice|costFormatter }}" key="2" row="0" col="2" cssClass="normal-price"/> 
           <Label text="{{ salePrice|costFormatter }}" key="3" row="0" col="3" cssClass="sale-price"/> 

          </GridLayout> 

         </ListView.itemTemplate> 
        </ListView> 

我不明白为什么我得到

JS: Cannot find function or filter: costFormatter 

每一行中我的列表视图中我nativescript终端。我究竟做错了什么?

回答

1

看来你正在尝试创建一个所谓的“管道”。

import { Pipe, PipeTransform } from '@angular/core'; 

@Pipe({ 
    name: 'costFormatter', 
    pure: true 
}) 

export class CostFormatterPipe implements PipeTransform { 
    transform(price: string): string { 
    return "$ " + price; 
    } 
} 

然后确保你添加CostFormatterPipeDeclarations阵列模块要在使用它。

+0

我试图做到这一点,是的,但没有棱角! Nativescript应该没有角度,对吧? –

+0

对不起。我看到了那个管道,并假设你使用了Angular :) ..确定你可以在没有Angular的情况下使用NativeScript。你看过这个转换器的官方文档吗? https://docs.nativescript.org/angular/core-concepts/angular-data-binding.html#data-converters –

0

在此文档1页检查描述。关于ListView项目的特殊注意事项在页面下方约2/3处描述。基本上,在应用程序资源中注册您的转换器功能。希望能帮助你。它为我做了。