Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display or hide the div through binding

Tags:

knockout.js

For Eg:

In viewModel,

//Makes webApi call to get the data from some repository
function GetData() {
            var data = http.get(apiUrl)
            .success(function (result) {
                 if (result != null || result !='')
                 {
                    // success display the data
                    vm.dataDisplay;
                 }
               else {
                    vm.errorMsg('No data');

                }
            })

//viewModel

 var vm = {
            activate: activate,
            dataDisplay: ko.observableArray(),
            errorMsg:ko.observable(''),
           };
        vm.activate();
        return vm;

//view. Expected.

If( errorMsg == 'No Data')
{
// show errordata div and hides displayData div
<div class="errorData" data-bind="text:errorMsg"/>
}
else
{
// Show displayData div and hide errorData div
<div class="displayData" data-bind="text:dataDisplay" />
}

How to implement this through binding??

I can use ko attr or visible. But my requirement is to hide/show through binding only. Please suggest me how to do this? Thanks in Advance.

like image 280
user2333363 Avatar asked Apr 29 '13 19:04

user2333363


People also ask

How do I hide a div?

We hide the divs by adding a CSS class called hidden to the outer div called . text_container . This will trigger CSS to hide the inner div.

How do you hide an element in HTML?

To hide an element, set the style display property to “none”. document.


1 Answers

You are right, you just need to use the visible binding, which would only show the HTML element if the value of the observable is NOT a null, undefined, or empty string. This should work:

<div class="errorData" data-bind="visible: errorMsg, text:errorMsg"/>

<div class="displayData" data-bind="visible: dataDisplay, text:dataDisplay" />

Also, if "dataDisplay" is indeed an array, you have to use:

<div class="displayData" data-bind="visible: dataDisplay().length, text:dataDisplay" />
like image 183
Jalayn Avatar answered Oct 21 '22 01:10

Jalayn