angularjs - 包含插值的 JS 字符串
angularjs - JS string containing interpolation
假设我的 Web 应用程序正在从后端获得 json 响应,如下所示:
[
{id:1, description: 'this is an example 1, **value is ###**'},
{id:2, description: 'this is an example 2, **value is ###**'},
{id:3, description: 'this is an example 3, **value is ###**'}
]
这里有一些格式语法。被 **
包围的文本表示 加粗 .
这部分很简单。我只需要搜索 **
并将其替换为 <b></b>
,然后在模板中我使用 ng-bind-html
.
现在有 ###
。这意味着我必须用一些动态变化的变量来替换它。如果整个字符串是硬编码的,我们可以在模板中轻松地做到这一点:
<div>this is example 1, value is {{someVariable}}</div>
如何从 Javascript 构造这样的字符串?
可以使用自定义过滤器,例如:
angular.module('myApp')
.filter('htmlReplace', function() {
// `input` is the description string, otherVar is `someVariable` in view
return function(input, otherVar) {
let html = input.replace(...// do your replacing
return html;
}
})
查看
<div ng-bind-html="obj.description | htmlReplace: someVariable"></div>
假设我的 Web 应用程序正在从后端获得 json 响应,如下所示:
[
{id:1, description: 'this is an example 1, **value is ###**'},
{id:2, description: 'this is an example 2, **value is ###**'},
{id:3, description: 'this is an example 3, **value is ###**'}
]
这里有一些格式语法。被 **
包围的文本表示 加粗 .
这部分很简单。我只需要搜索 **
并将其替换为 <b></b>
,然后在模板中我使用 ng-bind-html
.
现在有 ###
。这意味着我必须用一些动态变化的变量来替换它。如果整个字符串是硬编码的,我们可以在模板中轻松地做到这一点:
<div>this is example 1, value is {{someVariable}}</div>
如何从 Javascript 构造这样的字符串?
可以使用自定义过滤器,例如:
angular.module('myApp')
.filter('htmlReplace', function() {
// `input` is the description string, otherVar is `someVariable` in view
return function(input, otherVar) {
let html = input.replace(...// do your replacing
return html;
}
})
查看
<div ng-bind-html="obj.description | htmlReplace: someVariable"></div>