在模板中使用日期,百分比和货币管道时遇到同样的问题 -
例如,我使用简单的百分比管道:
{{ .0237| percent:'1.2-2' }}
在Chrome上运行时可以正常运行,但是当我部署到iOS设备时,它会抛出此错误:
" EXCEPTION:ReferenceError:无法找到变量:[{{{{{{{{{{百分比:' 1.2-2' } ..."
还有其他人遇到过这个问题吗?任何建议或帮助将不胜感激!谢谢!
答案 0 :(得分:67)
这是因为它依赖于内部化API,目前并非在所有浏览器中都可用(例如,不在iOS浏览器上)。
这是known issue(beta.1)。
您可以尝试使用polyfill for Intl。
为此,您可以使用CDN版本,并将其添加到index.html:
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en"></script>
或者,如果您使用Webpack,则可以使用NPM安装Intl模块:
npm install --save intl
并将这些导入添加到您的应用中:
import 'intl';
import 'intl/locale-data/jsonp/en';
答案 1 :(得分:11)
有一个快速解决方案。添加
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en"></script>
到<script src="cordova.js"></script>
条目之前的index.html文件。
请参阅此github回答https://github.com/angular/angular/issues/3333#issuecomment-203327903
答案 2 :(得分:1)
或者另一种解决方案是自己编写这些管道。例如,对于日期,您可以使用moment.js,或者这是货币管道的示例:
import { Pipe, PipeTransform } from '@angular/core'
@Pipe({ name: 'currency' })
export class CurrencyPipe implements PipeTransform {
constructor() {}
transform(value: string, currencyString: string ) {
let stringOnlyDigits = value.replace(/[^\d.-]/g, '');
let convertedNumber = Number(stringOnlyDigits).toFixed(2);
return convertedNumber + " " + currencyString;
}
}
此管道正在改变货币。百分比管道的工作方式几乎相同。正则表达式过滤所有数字,包括浮点数的点。
答案 3 :(得分:0)
这是我对RC3的所作所为。我认为它也适用于RC4。
键入ionic g pipe pipe-transform
清除代码以删除@Injectable
。另外,使用camel-case来命名如下。实施PipeTransform
。
import { Pipe, PipeTransform} from '@angular/core';
/**
* Takes a number and transforms into percentage upto
* specified decimal places
*
* Usage:
* value | percent-pipe: decimalPlaces
*
* Example:
* 0.1335 | percent-pipe:2
*/
@Pipe({
name: 'percentPipe'
})
export class PercentPipe implements PipeTransform {
/**
* Takes a number and returns percentage value
* @param value: number
* @param decimalPlaces: number
*/
transform(value: number, decimalPlaces:number) {
let val = (value * 100).toFixed(decimalPlaces);
return val + '%';
}
}
在app.module
添加到declarations
数组中。
然后在html中使用它就像上面的示例用法一样。 这是我的例子
<ion-col *ngIf="pd.wtChg < -0.05 || pd.wtChg > 0.05" width-25 highlight>
{{pd.wtChg | percentPipe: 2}}
</ion-col>
请注意,如果有人需要额外的帮助,我也会使用* ngIf和一个高亮指令。显然没有必要。