In Internet Explorer 8, angular's $window service may sometimes return undefined

I've developed a custom directive called slideshow with some scope variables that are two-way bound to ng-style. This directive functions as a responsive carousel that adjusts based on the window height retrieved using the $window service.

During testing in an IE8 virtual machine, I encountered an issue where the ng-style did not apply any styles in IE8 due to the $window service being undefined. Any suggestions on how to resolve this and make it function properly?

Display:

This feature works flawlessly on modern browsers:

JavaScript: slideshow directive

'use strict';

angular.module('alexApp')
  .directive('slideshow', function($window){
  return {
      restrict: 'A',
      templateUrl: 'template1.html',
      controller: function($scope, Pages) {
        $scope.adPageData = Pages;
        $scope.adpageLength = $scope.adPageData.length;
      },
      link: function postLink(scope, element, attrs) {


       var targetRatio = 0.8419689;
       var navigationOffset = 92;
       var currentPageIndex = 0;

       scope.initializeWindowSize = function() {
         scope.pageCollectionWidth = $window.innerWidth;
         scope.pageCollectionHeight = $window.innerHeight;
         scope.pageCollectionWidthTotal = scope.pageCollectionWidth + 'px';
         scope.properPageWidth = ( scope.pageCollectionHeight-navigationOffset)*targetRatio + 'px';

         scope.properPageWidthLength = ((scope.pageCollectionHeight-navigationOffset)*targetRatio)*scope.adpageLength + 'px';
         scope.leftPageOffset = scope.pageCollectionHeight/4+'px';
         scope.currentPageOffset = currentPageIndex*(-(scope.pageCollectionHeight-navigationOffset)*targetRatio)+'px';

       }

       scope.initializeWindowSize();
        //alert('initi');


       return angular.element($window).bind('resize', function() {
        scope.initializeWindowSize();

        //alert('resized');
        return scope.$apply();


      });
      }
  };
});     

HTML - template1.html:

<script type="text/ng-template" id="template1.html">
    <div class="weekly-viewport" ng-style="{width:pageCollectionWidthTotal}">
        <ul class="page-collection" ng-style="{width:properPageWidthLength, left:leftPageOffset, marginLeft:currentPageOffset }">
         <li class="page-layout" ng-repeat="page in adPageData.pages" ng-style="{width:properPageWidth}">
              <ul class="page shop-local-page">
                  <li class="imageurl"><img ng-src="{{page.imageurl}}" alt="" /></li>
              </ul>
          </li>
      </ul>
    </div>
  </script>

Sample pages factory

var app = angular.module('alexApp');
app.factory('Pages', function() {

    var Pages = {};
    Pages = {
      pages': [
            {
            imageurl: 'http://placekitten.com/200/300'
            },
            {
            imageurl: 'http://placekitten.com/200/300'
            }
          }
      }
  });

Answer №1

The issue is not the absence of the $window service - instead, it is related to IE8's inadequate support for window.innerHeight/Width.

If you are utilizing jQuery, consider using $(window).height()/width().
For those not using jQuery, here is a workaround for IE:

scope.pageCollectionWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
scope.pageCollectionHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Teach me how to utilize Import / require() in Static Folder

I've been attempting this task for a while, but I'm unsure how to incorporate import or require into the express static folder. When I try to use it, I receive an error stating "require not defined" which makes sense since these are not supported ...

What could be causing Nextjs13 to fail in recognizing an authentication route, resulting in a 404 error?

I have been working on a project utilizing NextJs v13 with Strapi v4 as the backend. My project includes separate layouts for the site, login, and dashboard. While working on the login section, I implemented NextAuth for authentication. However, upon submi ...

Choose only the options that are present in both arrays

I am working on creating a multiple select feature that displays all nodes, but only checks the ones that are present in 2 arrays. My front end is developed using Angular 8 and TypeScript. private mountSelect(nodesInRelation, lineApiKey) { console.lo ...

Detecting errors on the client side with JSON payload in Next.js and a personalized server

Working with Next.js and a custom Express server, I've encountered an issue regarding basic API error handling. I have set up a simple error handling middleware that looks like this: app.use((err, req, res) => { res.status(400).send(message); ...

Get the nearest offspring of the guardian

I have a main 'container' div with multiple subsections. Each subsection contains 1 or 2 sub-subsections. Let's say I have a variable that holds one of the subsections, specifically the 4th subsection. This is the structure:container > s ...

When converting a .ts file to a .js file using the webpack command, lengthy comments are automatically appended at the end of

As a backend developer, I recently delved into UI technologies and experimented with converting TypeScript files (.ts) to JavaScript files (.js) using the webpack command. While the conversion works well, the generated .js file includes lengthy comments at ...

Can we avoid the error callback of an AJAX request from being triggered once we have aborted the request?

Initially, I encountered a challenge where I needed to find a way to halt an AJAX request automatically if the user decided to navigate away from the page during the request. After some research, I came across this helpful solution on Stack Overflow which ...

Simultaneously iterate through two recursive arrays (each containing another array) using JavaScript

I have two sets of arrays composed of objects, each of which may contain another set of arrays. How can I efficiently iterate through both arrays and compare them? interface items { name:string; subItems:items[]; value:string; } Array A=['parent1&ap ...

Free up MySQL connections within a Promise.All implementation

At the moment, I am facing issues with releasing MySQL connections from a connection pool. Interestingly, when I release connections in a synchronous "for" loop, everything works fine. However, when I attempt to release them asynchronously using Promise.Al ...

Unable to associate ngModel because it is not recognized as a valid property of the "Component"

Currently, I am in the process of creating a custom form component using Angular 4. I have included all necessary components for ngModel to function properly, but unfortunately, it is not working as expected. Below is an example of my child component: ex ...

Encountered a cross-domain error with node.js and jQuery: ERR_CONNECTION_REFUSED

Just beginning my journey with Node.js. I've set up a basic node/express application that serves a single webpage featuring a button. When clicked, this button triggers a jQuery ajax request to an Express route. The route callback then makes an http ...

File upload failed with the Easy Upload Adapter in ckeditor

I am experiencing an issue when trying to upload an image. Despite researching the error, I have not been able to find a solution that works. My code is written in Express.js with ejs and specifically relates to the addPost.ejs file. <!DOCTYPE html& ...

The state returned by React Redux does not meet the expected results

I recently implemented a like function on the backend using Node and MongoDB. This function successfully returns the post with an updated likes counter, which I tested using Postman. The post object contains properties such as likes, _id, by, createdAt, an ...

The KeyboardAvoidingView disrupts the structure of the flexbox layout

Check out this code snippet: return ( <KeyboardAvoidingView style={{ flex: 1 }} behavior="padding" enabled> <View style={style.flex1}> <View style={style.imageContainer}> <Image style={style.image} ...

The JUnitXmlReporter from jasmineReporters is failing to produce an XML report

I am facing an issue with the JunitXML reporter as it is not generating the xml file. I execute the test using 'protractor example-test.js' command, but even though there are no errors, the file is not being generated. Can someone please assis ...

What is the best practice for using templates in a constructor versus connectedCallback?

Should I apply template in the constructor or connectedCallback of a custom element? In my experience, when I apply it in connectedCallback, sometimes attributeChangedCallback is called before and I can't query for elements. export class TestElement ...

issues with jasmine angularjs tests exhibiting erratic outcomes

During the execution of my unit tests, I often encounter a scenario where some random test(s) fail for a specific controller without any apparent reason. The error messages typically look like this: Expected spy exec to have been called with [ Object({}) ...

Understanding the syntax for matching files and paths in Node/JavaScript using glob, including the use of wild

I stumbled upon http://gruntjs.com/configuring-tasks#globbing-patterns and found it to be the most useful reference so far. I have come across the following statement multiple times: For more on glob pattern syntax, see the node-glob and minimatch docu ...

The usage of nextTick in Vue.js and its role in updating components

Although I am a beginner with vue.js and have a basic understanding of it, I came across a sample code utilizing nextTick() today. Trying to comprehend its purpose led me to explore the documentation, which ended up complicating things further and leavin ...

Renaming ngModel in an AngularJS directive's "require" attribute can be achieved by specifying a different alias

I need help with a basic AngularJS directive: <my-directive ng-model="name"></my-directive> I want to change the "ng-model" attribute to "model", but I'm unsure how to pass it to the "require" option in the directive. Here is the full co ...