我有一个处理不同货币的应用程序。我从 Web 服务获取货币符号并将该符号存储在 Controller 的 $scope 中。
$scope.symbol = '€';
当我尝试在 html 中显示时,
这是有效的:
{{ 1500 | currency:"€" }}
这是行不通的
{{ 1500 | currency:symbol }}
here's a plunker.有什么想法吗?
最佳答案
如果您想绑定(bind) html 或标记,您需要使用“ng-bind-html”并在您的 Controller 上将内容标记为受信任。我不知道如何使用 mustache 绑定(bind)机制执行此操作。但这是我们在需要绑定(bind)标记时一直使用的方法。
- 使代码在 Controller 中受信任
- 将过滤器包装在自定义过滤器中 - 限制是您仍然需要 ng-bind-html
以下是您可用的 3 个选项:
Controller
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$sce) {
$scope.nonTrustedSymbol = '€';
$scope.trustedSymbol = $sce.trustAsHtml('€');
})
.filter('currencyWithNumberFilter', ['$filter','$sce',
function ($filter, $sce) {
return function (input, curr) {
var formattedValue = $filter('number')(input, 2);
return $sce.trustAsHtml(curr + formattedValue);
}
}]
)
.filter('currencyWithCurrencyFilter', ['$filter','$sce',
function ($filter, $sce) {
return function (input, curr) {
var formattedValue = $filter('currency')(input,curr);
return $sce.trustAsHtml(formattedValue);
}
}]
);
标记
<body ng-controller="MainCtrl">
"Vanilla" controller & number filter:
<span ng-bind-html=trustedSymbol></span>{{ 1500 | number:2 }}
<br/>
Custom filter, internally making use of Number filter for formatting:
<span ng-bind-html="1500 | currencyWithNumberFilter:nonTrustedSymbol"></span>
<br/>
Custom filter, internally making use of Currency filter for formatting:
<span ng-bind-html="1500 | currencyWithCurrencyFilter:nonTrustedSymbol"></span>
</body>
工作样本
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope,$sce) {
$scope.nonTrustedSymbol = '€';
$scope.trustedSymbol = $sce.trustAsHtml('€');
})
.filter('currencyWithNumberFilter', ['$filter','$sce',
function ($filter, $sce) {
return function (input, curr) {
var formattedValue = $filter('number')(input, 2);
return $sce.trustAsHtml(curr + formattedValue);
}
}]
)
.filter('currencyWithCurrencyFilter', ['$filter','$sce',
function ($filter, $sce) {
return function (input, curr) {
var formattedValue = $filter('currency')(input,curr);
return $sce.trustAsHtml(formattedValue);
}
}]
);
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
"Vanilla" controller & number filter:
<span ng-bind-html=trustedSymbol></span>{{ 1500 | number:2 }}
<br/>
Custom filter, internally making use of Number filter for formatting:
<span ng-bind-html="1500 | currencyWithNumberFilter:nonTrustedSymbol"></span>
<br/>
Custom filter, internally making use of Currency filter for formatting:
<span ng-bind-html="1500 | currencyWithCurrencyFilter:nonTrustedSymbol"></span>
</body>
</html>
关于AngularJS - 从范围加载 HTML 实体作为货币符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25842194/