7

I am new to AngularJS and recently introduced it into my application. I am trying to re-write some of my existing jQuery code in my controllers, however, on one occasion, i am using:

jQuery:

if ($(window).width() < 700) {

   $('.productsHeading').on('click', function() {

       $(".productsBody").hide();
       $(".aboutUsBody").show();

   });
}

I can get around the .hide() and .show() using ng-hide="productsBody" and ng-hide="aboutUsBody" within my DIVs.. These are handled through a ng-click="productsheading()".. However, the issue i am facing is, how do i handle the:

if ($(window).width() < 700) {

In AngularJS? I am using AngularJS v1.1.5

Oam Psy
  • 8,555
  • 32
  • 93
  • 157

2 Answers2

6

In AngularJS if you want to do changes in HTML or DOM manipulation then recommended or best practices is to use the directive for the same.

Write a directive may be below links are helpful:

AngularJS event on window innerWidth size change

http://jsfiddle.net/jaredwilli/SfJ8c/

HTML for the Directive

<div ng-app="miniapp" ng-controller="AppController" ng-style="style()" resize>window.height: {{windowHeight}}
    <br />window.width: {{windowWidth}}
    <br />
</div>

Javascript Code for the Directive

    app.directive('resize', function ($window) {
    return function (scope, element) {
        var w = angular.element($window);
        scope.getWindowDimensions = function () {
            return {
                'h': w.height(),
                'w': w.width()
            };
        };
        scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
            scope.windowHeight = newValue.h;
            scope.windowWidth = newValue.w;

            scope.style = function () {
                return {
                    'height': (newValue.h - 100) + 'px',
                        'width': (newValue.w - 100) + 'px'
                };
            };

        }, true);

        w.bind('resize', function () {
            scope.$apply();
        });
    }
})
Community
  • 1
  • 1
JQuery Guru
  • 6,943
  • 1
  • 33
  • 40
  • 1
    Do you mind explaining the code here? What's the `scope.style` and `- 100` for, where are you reusing `'h' : w.height()` – Holly Dec 18 '16 at 06:37
  • Scope.style is function called from HTML. Referrer this URL for details http://jsfiddle.net/jaredwilli/SfJ8c/ – JQuery Guru Dec 20 '16 at 06:58
2

Most implementations that you will find for retrieving element sizes will have different behavior depending on the browser.

Your best choice is to use jQuery's width method which will have same result on any browser.

Btw, there is no need to completely remove jQuery if you are changing to Angular.

For some features jQuery will probably offer the best implementation.

Catalin MUNTEANU
  • 5,618
  • 2
  • 35
  • 43