Search code examples
javascripthtmlcssangularjsng-style

ng-style as a variable passed to directive


I know most people use style as such:

ng-style="{'background-color': someVariable"}
// or as a variable
ng-style="stage.style"  

I would like to have a scope variable which I just compute:

// controller
$scope.stage.style = stageFactory.init(); // returns Object {width: 1155, height: 1304}

What I really want to do is pass that to a directive:

app.directive( 'stage', function( $window ){
  return {
    restrict: 'E',
    transclude: true,
    scope: {
      mystyle: '='
    },
    template: '<div ng-style="mystyle" ng-transclude></div>',
    link: function( scope, attr ){
      if( ! scope.mystyle.width ){
        scope.mystyle.width = $window.innerWidth;
      }
      if( ! scope.mystyle.height ){
        scope.mystyle.height = $window.innerHeight;
      }

      // scope.mystyle = {
      //   width: scope.width,
      //   height: scope.height 
      // };

      console.log( 'style in directive', scope.mystyle );
    }
  };
});

What I don't see is the style being compiled, how do I get the style to show?

My (in)complete code so far: https://plnkr.co/edit/5wwKJ445IqPGTNGGRDIv?p=preview


Solution

  • All I can say is the width & height value should have px appended to it, otherwise they will considered as invalid CSS

    $scope.stage.style = {width: '1155px', height: '1304px'}