javascript - $watch fires only on first update of window.innerWidth -


i'm trying setup app watch window.innerwidth property , add property $scope based on width. works first time, not on resize after that. $digest method not being called? if why not?

module

//initialize angular module include route dependencies  var app = angular.module("selfservice", ['ngroute']);  app.config(function ($routeprovider) {    $routeprovider        .when('/', {            templateurl:"partials/login.html",            controller:"login"        }); }); 

controller

app.controller("login", ['$scope', function ($scope) {   $scope.$watch(      function () {         return window.innerwidth;     },      function (newval, oldval) {         if (newval < 700) {             $scope.classexpand = 'expand';         } else {             $scope.classexpand = '';         }          console.log(newval, oldval);     });    }]); 

view

<div class="small-12 column">             <a href="/portal" class="button radius large {{classexpand}}">sign in</a> </div> 

this works first time, if refresh screen after resizing it, expand class applied, when resize it, nothing happens, console.log function doesn't fire

resizing window doesn't cause angular re-run $digest loop, window.innerwidth's value checked when else causes it.

you should instead use directive (ie. don't work in controller), binding window.onresize event:

.directive('watchresize', function(){   return {     restrict: 'a',     link: function(scope, elem, attr) {       angular.element(window).on('resize', function(){         scope.$apply(function(){           scope.classexpand = (window.innerwidth < 700) ? 'expand' : '';         });       });     }   } }); 

in case, call scope.$apply. causes $digest loop run following event, outside of angular context.

you can use directive decorate element on same scope variable you're changing:

<div watch-resize>   {{ classexpand }} </div> 

demo (best viewed full-screen)


Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -