4

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.

1
  • 2
    I didn't write this fiddle, but it shows how to handle window resize events as a directive jsfiddle.net/bY5qe . I believe that directives are the preferred "Angular" way to handle DOM manipulation. Commented Apr 17, 2013 at 11:05

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this input, this is much nicer :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.