首页 > 解决方案 > 如何在 AngularJS 中使用 Lodash _.template

问题描述

你能解释一下如何使用 Lodash_.template来通过 .html 文件从脚本中获取一些价值{{data}}吗?

例如:

script.js中,我对我的数据对象和view.html进行了一些更改。我想data改变{{data}}

如何使用 lodash_.template()解决这个问题?

标签: angularjslodash

解决方案


lodash 模板功能不允许您从文件构建模板(但您可以与 Webpack 结合使用)。它与 AngularJS 模板完全无关。然而,在某些情况下,在 AngularJS 内部使用是有意义的,例如构建带有模式等的字符串列表。

您将模板字符串编译为一个函数,您可以根据需要随时调用这些值:

const executor = _.template("Hello <%= name %>, my old friend!");
console.log(executor({name: 'Alice'})); // Hello Alice, my old friend!
console.log(executor({name: 'Bob'})); // Hello Bob, my old friend!

您还可以使用条件、循环等:https ://lodash.com/docs/4.17.15#template


推荐阅读