Search code examples
javascripthtmlimagewindows-phone-8.1winjs

unable to bind image to img tag


I am practicing Windows Phone development using WinJS and I have the following code which parses JSON received from a particular URL. And using the images to be bound to a list view in an HTML page,

JavaScript code:

 WinJS.xhr({ url: urlToBeUsed }).then(
     function (sportsResponse) {
         var sportsJSON = JSON.parse(sportsResponse.responseText);
         var listItems = sportsJSON.Videos.Data;

         for (var i = 0; i < listItems.length; i++) {
             var imageList = listItems[i].Items;
             var count = imageList.length;
             if (count > 0) {

                 listItems[i].Items[0].Images.forEach(imageIteration);

                 function imageIteration(value, index, array) {
                     var picture = value.Url;
                     var name = value.title;

                     sportsImageList.push({
                         title: name,
                         picture: picture
                     });
                 }
             }
         }
         imageList.itemDataSource = sportsImageList.dataSource;
     })
 }

HTML Code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>

    <!-- WinJS references -->
    <script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
    <script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
    <script src="/js/navigator.js"></script>
    <link href="/css/default.css" rel="stylesheet" />
    <link href="/pages/home/home.css" rel="stylesheet" />
    <script src="/pages/sports/sports.js"></script>
  </head>
  <body>
    <!-- The content that will be loaded and displayed. -->
    <div class="fragment homepage" style="width:100%;height:100%;padding:10px">
      <div class="myTemplate" data-win-control="WinJS.Binding.Template">
        <div class="myItem">
          <img data-win-bind="src:picture" style="width:100px;height:100px" />
        </div>
      </div>
      <div id="imageList" data-win-control="WinJS.UI.ListView" data-win-bind="winControl.itemDataSource:sportsImageList.dataSource" data-win-options="{itemTemplate:select('.myTemplate')}"></div>
    </div>
  </body>
</html>

I have tried many ways to bind the URL to the Image, but on the screen I can only see the links but not the actual images. Where am I wrong? All help and suggestions appreciated. Thank you!


Solution

  • I believe your error is in your assignment line, remember that itemDataSource is a property of the ListView control. As it is in your code you're assigning that property to the imageList element.

    Change it to this:

    imageList.winControl.itemDataSource = sportsImageList.dataSource;