Ashrant Kohli
Ashrant Kohli

Reputation: 83

Is there a way to modify a json string within the html while reading it in?

so I have a complex object structure in my JSON which is a list with many attributes for each element. I want to be able to access the name attribute and output it whole ie: "task one" and add an href on the fly while loading the text which will reference "link-to-task-one".

I'm using knockout js and this is what the line looks like

<a class="this-class" data-bind="text: taskName attr: {href: '#link-to-'+taskName.replace(/\s+/g,'-')}"></a>

I know the js function replace doesnt work in html docs, I just want to know if theres a way to force json to be rendered like maybe within certain tags, or if someone can help me figure out a method to put in there that wouldn't take too much time.

Or if I'm being stupid and should just add another attribute called 'ref' or something in my JSON

Upvotes: 0

Views: 44

Answers (1)

tyler_mitchell
tyler_mitchell

Reputation: 1747

Why not add a computed to your model:

self.link = ko.computed(function () {
    return '#link-to-' + self.taskName().replace(/\s+/g,'-');
}, self);

Then:

<a class="this-class" data-bind="text: taskName, attr: { href: link }"></a>

Upvotes: 4

Related Questions