【问题标题】:ng-style as a variable passed to directiveng-style 作为变量传递给指令
【发布时间】:2016-07-05 18:38:30
【问题描述】:

我知道大多数人都这样使用样式:

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

我想要一个我刚刚计算的范围变量:

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

我真正想做的是将它传递给指令:

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 );
    }
  };
});

我没有看到正在编译的样式,如何让样式显示?

到目前为止我的(中)完整代码: https://plnkr.co/edit/5wwKJ445IqPGTNGGRDIv?p=preview

【问题讨论】:

    标签: javascript html css angularjs ng-style


    【解决方案1】:

    除了答案:

     // in directive
          if( !isNaN( scope.mystyle.width ) ){
            scope.mystyle.width += 'px';
          }
          if( !isNaN( scope.mystyle.height ) ){
            scope.mystyle.height += 'px';
          }
    

    【讨论】:

      【解决方案2】:

      我只能说width 和height 值应该附加px,否则它们将被视为无效CSS

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

      【讨论】:

      • @SoluableNonagon 很高兴知道这一点.. 谢谢 :-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-30
      相关资源
      最近更新 更多