I have the following model:
{
content: "Hello world, this is a sample content",
notes: {
content: "side note, some text here.",
index: 2
}
}
I like the above model to be compiled to the following HTML:
<div class="content">
Hello world,*
<div class="note">side note, some text here.</div>
this is a sample text.
</div>
How can this be done?
As far as I know the best way is to use directive, like <div content="{{ content }}"></div>.
I tried to write this directive and use the compile service without much success yet...
I want to inject the note compiled with its HTML to the content after the second word (see the note index position is 2).
I have here two templates, one for the content and the second for the note. I want to compile the note with its view and then enter it to the content text after the second work. Then, I'd like so compile the content against its view.
I think I follow. The notes will be styled to look like margin notes or as a tooltip, right?
This should be pretty easy to accomplish in a directive. I'd instantiate it like this (though implementation details are up to you):
<div note-section
note="{{notes.content}}"
note-index="{{notes.index}}"
content="{{content}}">
</div>
Alright. Then, within your link function, you have access to all of these attributes. So then I would $watch for changes, and when they occur, search the scope.content string for the appropriate index where scope.noteIndex words lives, and then slice the string into two pieces, inserting a note template like follows between it:
var tmpl, childElement;
tmpl = beforeNote + '<span note="{{note}}"></span>' + afterNote;
childElement = $compile( tmpl )( scope );
element.append( childElement );
The note element is a directive that has an isolate scope (for security).
Then the rendered DOM node would match your goal above. This is very generic and there are zillions of variations that depend on your implementation, but this is the general pattern I'd follow.
Take a stab at it on Plunker or jsFiddle, and post what you come up with!
Question: Why does the note have to appear in the HTML at a particular position (index), why can't it always appear before or after? Is there a specific reason, or is this to support styling?
If you are trying to support styling, there are better and easier ways to accomplish this, such as using float: right, etc.
As far as I know, there is no built in way to accomplish such output. If you must have that specific HTML, you can try the following jsFiddle: http://jsfiddle.net/69ApD/.