0

I'm trying to call a css class in one of the span tag that is within a template and it doesn't seem to work

Here is my viewmodel:

var data = [
    {
     'id': '1',
     'firstName': 'Megan',
     'lastName': 'Fox',
     'picture': 'images/01.jpg',
     'bio': 'Megan Denise Fox w' 
    },
    {
     'id': '1',
     'firstName': 'asdf',
     'lastName': 'asdf123',
     'picture': 'images/02.jpg',
     'bio': 'hwkhjkds lkawhkhkbs iklhskjha' 
    }
];

var viewModel = {
    people: ko.observableArray(data),
    myClass: ko.observable('test')
};
ko.applyBindings(viewModel);

And this is my view:

<h1>Profile Viewer</h1>
<div id="profilesTabViewer">
    <ul id="profileTab" data-bind="template: { name: 'profileListTemplate', 
                                               foreach: people }">
    </ul>        
</div>

<script type="text/html" id="profileListTemplate">
    <li>
        <span data-bind="text: firstName, css: myClass"></span>            
    </li>
</script>

I have shared the code in http://jsfiddle.net/du3QX/11/

2 Answers 2

1

Your binding is not correct. Your are traing to use myClass property, which should be an item in people observable array. But, according your view model, myClass is a property of root viewModel:

So you should add $root or $parent context (in your case can be used any) in your binding:

<span data-bind="text: firstName, css: $root.myClass"></span>

Update

I changed your demo, it works correct.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Alexander, I'm still not bale to bind my css class. In my application its under a folder css and when I try to use the css class binding the changes are not getting reflected on to my html page. I used both parent and root
@Vimal, check demo, please.
0

Your problem in myClass binding.

The ViewModel that is binded to your template is an object of people not the root/parent ViewModel, for example in first loop it 'll be

{
    'id': '1',
    'firstName': 'Megan',
    'lastName': 'Fox',
    'picture': 'images/01.jpg',
    'bio': 'Megan Denise Fox w'
}

Now you see it has no such property called myClass(it only exist in the root/parent ViewModel).

So, you need to change your binding in profileListTemplate template to be like this:

<span data-bind="text: firstName, css: $parent.myClass"></span>

OR

<span data-bind="text: firstName, css: $root.myClass"></span>

1 Comment

Thanks Ebram, I'm still not bale to bind my css class. In my application its under a folder css and when I try to use the css class binding the changes are not getting reflected on to my html page. I used both parent and root.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.