javascript - Conditionally styling the last element in a knockout.js foreach loop -
i have small chunk of code believe should work, line broken clarity here:
<!-- ko foreach: customer.address --> <span data-bind="style: { display: $index() === ($parent.data().length -1) ? 'inline-block' : 'block' }, text: $data.text"></span> <!-- /ko -->
my aim here loop around printing out span elements, of set display: block
, last set display: inline-block
. not appear matter how bracket conditional, doesn't work , returns error:
uncaught typeerror: unable process binding "foreach: function (){return customer.address }" message: unable process binding "style: function (){return { display:$index() ===($parent.data().length -1) ?'inline-block':'block'} }" messag...<omitted>...a'
modifying conditional otherwise evaluates true fine, e.g. `display: (1 === 1) ? 'inline-block' : 'block'. of note conditional check last element ok, under other circumstances, , came question:
knockout.js foreach binding test if last element
how should go conditionally applying style or other attribute last element in foreach loop? trying avoid having 2 <!-- ko if: -->
, 2 different <span>
lines, if that's what's needed let me know.
there no data()
property on $parent
.
in linked sample working because array called data
on parent.
you have array in customer.address
property need use that:
<!-- ko foreach: customer.address --> <span data-bind="style: { display: $index() === ($parent.customer.address.length -1) ? 'inline-block' : 'block' }, text: $data.text"></span> <!-- /ko -->
demo jsfiddle.
note: need write address()
if address
observable array $parent.customer.address().length
if don't want repeat array name can use with
binding wrap foreach
:
<!-- ko with: customer.address --> <!-- ko foreach: $data --> <span data-bind="style: { display: $index() === ($parent.length -1) ? 'inline-block' : 'block' }, text: $data"></span> <!-- /ko --> <!-- /ko -->
in case $parent
directly point array no need repeat "path".
demo jsfiddle.
however if want style last element , there no additional logic related can achieve using pure css3 last-child
selector.
demo jsfiddle.
Comments
Post a Comment