简体   繁体   中英

window resizing info in angular

I just published this fiddle thinking it could be helpful for people like me. It shows how plain javascript can be passed to an angular scope. In this case, the scope gets window innersize information.

http://jsfiddle.net/spacm/HeMZP/

For personal use, I'll pass to angular scope these informations:

  • width & heigth
  • orientation / orientation change
  • iframe detection
  • OS detection

using the navigator.platform variable

function isInIFrame(){
    return window.location !== window.parent.location;
}

function updateMediaInfoWH() {
    if((typeof(mediaInfo.inIFrame)!='undefined') && (!mediaInfo.inIFrame)) {
        mediaInfo.width = innerWidth;
        mediaInfo.height = innerHeight;
        updateMediaInfoOrientation();
    }
    tellAngular();
}

function tellAngular() {
    console.log("tellAngular");
    var domElt = document.getElementById('mainContainer');
    scope = angular.element(domElt).scope();
    console.log(scope);
    scope.$apply(function(){
        scope.mediaInfo = mediaInfo;
        scope.info = mediaInfo.width;
    });
}

Any comment is welcome.

I don't see a question to answer, so I'll assume your question is looking for input on your idea.

Getting going with Angular can be very different than the way you normally work, mainly because of their complete and total use of dependency injection.

You shouldn't have to "tell" Angular anything, you should be able to access all of this information through an injected dependency, an Angular service.

Using what you've shown me, it could look something like this:

my.MediaInfo = function($window) {
  this.window_ = $window;
  this.inIframe = $window.self !== $window.top;
  if(!this.inIFrame) {
    this.width = $window.innerWidth;
    this.height = $window.innerHeight;
  } else {
    this.width = this.height = ...;
  }
}

my.angular.controller = function($scope, mediaInfo) {
  // {width: X, height: Y, inIframe: false}
  $scope.mediaInfo = mediaInfo;
}

Then your Angular module would look like:

angular.module('module', [])
    .service('mediaInfo', my.MediaInfo)
    .controller('mainCtrl', my.angular.controller);

Hopefully, this is a good demonstration of how you should be getting data into Angular.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM