2016-06-22 64 views
0

我正在調查ES6,發現我喜歡的模板字符串。ES6 TemplateUrl like Angular2

隨着ES6模板字符串我能夠注入HTML這樣的:

$("#warning").html(` 
     <h1>Watch out!</h1> 
     <p>Unauthorized hockeying can result in penalties of up to 500 minutes.</p> 
`); 

反引號是ES6的非常有用的功能。

在AngularJs2中,您可以使用TemplateUrl並實際導入外部頁面。

這可以用ES6(沒有Angular2)完成,如果是的話如何?

+0

這是在已經ES6? https://ponyfoo.com/articles/es6-template-strings-in-depth – Ananth

+0

哦,要使用ES6而不使用Angular2,你需要像Babel或Traceur這樣的轉譯器。對於前節點,使用babel-cli你可以運行'babel-node es6script.js',你可以使用模板字符串 – Ananth

+0

我一直在使用ES6,沒有它在我的瀏覽器上。 jQuery的的混合和ES6: ..它工作正常 – Satch3000

回答

1

您的示例已經是ES6,但它並不總是有效,因爲模板字符串會考慮全部空格,包括您用於縮進代碼的空白。

你有幾個選項。

使用字符串連接:

$("#warning").html(
    `<h1>Watch out!</h1>` + 
    `<p>Unauthorized hockeying can result in penalties of up to 500 minutes.</p>` 
); 

我的優選的方法是加入數組:

$("#warning").html([ 
    `<h1>Watch out!</h1>`, 
    `<p>Unauthorized hockeying can result in penalties of up to 500 minutes.</p>` 
].join(''));