Sanjay Hp Sanjay Hp - 25 days ago 8
AngularJS Question

Custom directive not working if i change the name of the directive

I tried to implement a window resize custom directive and it works fine.

The problem is it works only if i use the directive name as resize.
Otherwise if i use different name as windowsize,it is triggered only at the time of page refresh.

here is the controller code

var app = angular.module('miniapp', []);

function AppController($scope) {
/* Logic goes here */
}

> > app.directive('windowsize', function($window){
> return function(scope,element){
> var w=angular.element($window);
> scope.getWindowDimension=function(){
> return{
> 'w': w.width()
> };
> };
> scope.$watch(scope.getWindowDimension, function (newValue, oldValue) {
> scope.windowWidth = newValue.w;
> console.log( scope.windowWidth);
>
> }, true);
> w.bind('windowsize', function () {
> scope.$apply();
> });
> };
> })



html code
<div ng-app="miniapp" ng-controller="AppController" windowsize>
window.height: {{windowHeight}}
<br />window.width: {{windowWidth}}
<br />
</div>

Answer

var app = angular.module('miniapp', []);

function AppController($scope) {
    /* Logic goes here */
}

 app.directive('windowsize', function($window){
         return function(scope,element){
             var w=angular.element($window);
             scope.getWindowDimension=function(){
                 return{
                      'w': w.width()
                 };
             };
              scope.$watch(scope.getWindowDimension, function (newValue, oldValue) {
              scope.windowWidth = newValue.w;
              console.log( scope.windowWidth); 
         }, true);
               w.bind('resize', function () {
             scope.$apply();
         });
        };
      })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
html code
<div ng-app="miniapp" ng-controller="AppController"  windowsize>
    window.height: {{windowHeight}}
    <br />window.width: {{windowWidth}}
    <br />
</div>

Here In this example you done everything correct but one small mistake, you bind event windowresize is not event so use resize and try it(I just correct for width only)

Comments