簡體   English   中英

使用ng-style將動態創建的CSS應用於組件

[英]Applying dynamically created CSS to a component using ng-style

我有一個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'
});

stylized-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}"但沒有任何區別。

我找到了一個解決方案,並認為我會在此處發布,以防將來其他人遇到此問題。

添加:

$scope.$apply()

生成CSS並將其存儲在控制器上之后,到圖像加載EventListener的末尾即可解決此問題。 我相信發生這種情況是因為圖像加載不在angularjs范圍內,所以當它完成時,angular不知道任何更改,因此不會更新ng樣式綁定。 強制它使用$ scope來更新綁定。$ apply()會更新ng樣式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM