virus virus - 1 month ago 7
AngularJS Question

angular js - scope.apply not working as expected

I am using angular material 1 and want to hide sidenave when window size not satisfy "gt-sm". Below is the controller code.

.controller('mainpageController',mainpageAction);

function mainpageAction($scope,$mdMedia,$window){
//state variable for mainpage.
$scope.sideNavVisibility = $mdMedia('gt-sm');

/* function definition for mainpage; bind this function using ng-click when user click on side menu */
$scope.showSideNav = function(defaultDisplay){
$scope.sideNavVisibility = true;
};
angular.element($window).bind('resize', function(){
console.log($mdMedia('gt-sm'));
$scope.$apply(function() {
$scope.sideNavVisibility = $mdMedia('gt-sm');
});
});
}


Below is the HTML template where I am using it.

<body md-theme="mainpage" ng-controller="mainpageController">
<div layout="row" layout-fill="true">
<md-sidenav class="md-sidenav-left" md-is-locked-open="{{sideNavVisibility}}" flex="none">


In console I am getting the correct value. When screen side is greate than 960px it is logging "true" value else "false". But still the change is not getting applied to view.

Here basically I want to show sidenav if screen size is more than 960px i.e. "gt-sm" or when not greater than "gt-sm" then when user click on side menu icon.

Answer

Remove the double curly brackets {{ }} from the expression furnished to the md-is-locked-open attribute:

<body md-theme="mainpage" ng-controller="mainpageController">
    <div layout="row" layout-fill="true">
    <md-sidenav class="md-sidenav-left"
                <!-- REMOVE double curly brackets 
                md-is-locked-open="{{sideNavVisibility}}"
                -->
                md-is-locked-open="sideNavVisibility"                     
                flex="none">

Double curly brackets converts the boolean value false to the string "false". In JavaScript the string "false" is truthy instead of falsy. In fact any string with a length greater than zero is truthy. This is one of the quirks of JavaScript.

For more information, see MDN JavaScript Reference - falsy