0
votes

I have two observables 1.Data and 2.Image(Making Ajax call to get the image. For this i am passing data Id). If image is found then i need to display the image and data as shown in below. For eg :

<div class="MainDiv">
        <div class="ImageDiv"><img id="img"  src:"/...image/" /></div>
        <div class="dataDiv" data-bind="text: data/>
</div>

suppose if image is not found then i need to hide the image div like

<div class="MainDiv">
        /* Hide this when no image  <div class="ImageDiv"><img src="" /> */
        <div class="dataDiv" data-bind="text: data/>
</div>

I used ko attr as shown in below: Var ImageFound contains boolean value. If true display image div & data div else display only data div.

<div  data-bind="attr: { class: ImageFound ? 'ImageDiv' : 'DataDiv' }">.

Can you please suggest how to do this?

Here is the viewModel code:

 // This function internally makes Ajax call for every data to get the corresponding image

        function LoadImages(result) {
            $.each(result, function (id, data) {
                if (data.ImageUrl != null) {
                    return http.get(Url +'/?imageId=' + data.ImageUrl)
                    .success(function (imageResponse) {

                        if (imageResponse == null || imageResponse == "") {
                        newItem.ImageFound= false;
                        }else {
                            var newItem = vm.Data()[id];
                            newItem.Image = "" + imageResponse;
                            newItem.ImageFound= true;
                            vm.data.replace(vm.data()[id],newItem)
                            vm.data(result);
                        }
                    })
                    .fail(function (exception) { }); 
2

2 Answers

0
votes

If ImageFound is an observable, then you need to call it as one:

<div data-bind="attr: { class: ImageFound() ? 'ImageDiv' : 'DataDiv' }">

Otherwise all you are doing is resolving whether the observable (which is just a function, as far as javascript is concerned) exists. And it always will exist, therefore will always resolve to true.

0
votes

You could also use the visible binding like this :

<div class="MainDiv">
  <div class="ImageDiv" data-bind="visible: ImageFound()">
    <img id="img"  src:"/...image/" />
  </div>
  <div class="dataDiv" data-bind="visible: !ImageFound(), text: data"/>
</div>