javascript - Embed the data itself inside foreach with Knockout -


i using knockout "foreach" given in following; trying iterate collection , print (bind) results html page. collection object "topics" list of topic objects.

and "topic" object has following attributes ; link , translation.

the link attribute stands for;

 < href ------ />  

the traditional binding provides solution ;

     self.loadtemplates = function() {          var booktopics = "<h5 class=\"book-nav-title\" data-bind=\"text: title\"></h5>\                          <ul id=\"navbookitems\" class=\"nav nav-stacked book-nav\">\                             <!-- ko foreach: topics -->\                                 <li><a data-bind=\"attr: { href: link, title: translation }\"><span data-bind=\"text: translation\"></span><i class=\"pull-right\"></i></a></li>\                             <!-- /ko -->\                          </ul>";           self.templateengine.addtemplate("ui_booktopics_tmplt", booktopics);     } 

but specified, link attribute href attribute itself, that's why bind incoming link value <li> block is. expect put value of link $link. there way of doing ?

self.loadtemplates = function() {          var booktopics = "<h5 class=\"book-nav-title\" data-bind=\"text: title\"></h5>\                          <ul id=\"navbookitems\" class=\"nav nav-stacked book-nav\">\                             <!-- ko foreach: topics -->\                                 <li>$link<span data-bind=\"text: translation\"></span><i class=\"pull-right\"></i></a></li>\                             <!-- /ko -->\                          </ul>";          self.templateengine.addtemplate("ui_booktopics_tmplt", booktopics);     } 

briefly,

the link has following value ;

  <a href="/bookhistory.html" >history101</a> 

the expected <li> generated ;

 <li><a href="/bookhistory.html"><i class="pull-right"> history101   </i></a></li> 

topic object sample :

topic = {     link: "<a href='/bookhistory.html'>history101</a>",     originaltext: "history101",     section: "first",     translation: "history101" } 

i think should use custom binding achieve want.

ko.bindinghandlers.linkme = {     init: function(element, valueaccessor, allbindings, viewmodel, bindingcontext) {         var value = valueaccessor();         var link = value.link.replace(value.originaltext, '<i class="pull-right"></i>'+ value.translation);         $(element).html(link)     } } 

with following html :

<ul id="navbookitems" class="nav nav-stacked book-nav" data-bind="foreach: topics">     <li data-bind="linkme: $data"></li> </ul> 

i've made fiddle here.

i agree replace function kind of hacky :s


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -