使用ng-style将动态创建的CSS应用于组件

时间:2017-02-23 17:44:00

标签: javascript angularjs angularjs-components

我有一个angularjs组件来创建风格化的图片,但是第一次访问页面时样式没有正确应用(刷新页面显示正确的样式)。应用的CSS是根据要设置样式的图像的高度和宽度属性动态生成的。

有人可以告诉我为什么CSS应用于重新加载而不是原始加载,以及如何修复它以便在第一次加载页面时应用CSS?谢谢!

在HTML中我创建了一个风格化的图片:

<stylized-picture image-source="someImage.jpg"></stylized-picture>

stylizedPicture组件

.component('stylizedPicture', {
    templateUrl: 'src/components/stylized-picture.template.html',
    bindings: {
      imageSource: '@imageSource',
    },
    controller: 'StylizedPictureController as stylizedPictureController'
});

程式化-picture.template.html

<div ng-style="stylizedPictureController.outerCSS">
    <div ng-style="stylizedPictureController.innerCSS"></div>
       <div ng-style="stylizedPictureController.imgDivCSS">
           <img ng-src="{{stylizedPictureController.imageSource}}">
       </div>
    </div>
</div>

stylizedPictureController :CSS基于图像宽度/高度。

.controller('StylizedPictureController', StylizedPictureController);

StylizedPictureController.$inject = ['$scope'];
function StylizedPictureController($scope) {
    var ctrl = this;

    ctrl.$onChanges = function() {
      var img = new Image();
      img.addEventListener("load", function() {
        ctrl.imgWidth = img.naturalWidth;
        ctrl.imgHeight = img.naturalHeight;

        // Fancy stuff to stylize image based on img h/w removed
        // simplified for example
        var paddingBottom = 100;
        ctrl.paddingBottom = paddingBottom;
        ctrl.outerCSS = {"padding-bottom: " + paddingBottom + "%"};
        ctrl.innerCSS = {"padding-bottom: " + paddingBottom + "%"};
        ctrl.imgDivCSS = {"padding-bottom: " + paddingBottom + "%"};
      });
      img.src = ctrl.imageSource;
    };
};

我尝试使用image.onLoad()方法而不是ctrl.$onChanges功能/ img eventListener,但结果相同。我还尝试设置ng-style内联,例如ng-style="{'padding-bottom': stylizedPictureController.paddingBottom}"但它并没有什么不同。

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,并认为我会在此发布,以防将来有人遇到此问题。

添加:

run = 0
function getLowestPrice(id){
   $.get('/items/' + id + '/privatesaleslist', function(data){
      var html = $(data);
      var lowestPrice = parseInt($('.currency-robux', html).eq(0).text().replace(',', ''));
      console.log(lowestPrice);
   })
}
while (run < 100) 
{
getLowestPrice(362081769);
run = run + 1
}

到图像加载EventListener的末尾,在生成CSS并将其存储在控制器上之后,修复了该问题。我相信这种情况正在发生,因为图像负载超出了angularjs范围,所以当它完成时,angular并不知道任何事情已经改变,因此不会更新ng-style绑定。强制它用$ scope更新绑定。$ apply()更新ng-style。