Angular.js: ページの読み込み時に要素の高さを設定する 質問する

Angular.js: ページの読み込み時に要素の高さを設定する 質問する

私はAngularJS初心者です。グリッドを作成したいのですが(ngグリッド) 高さはウィンドウの高さによって決まります。$('.gridStyle').height($(window).height() - 100);

私は指示を書きました:

app.directive('resize', function($window) {

    return function(scope, element) {

        function applyHeight() {
            scope.height = $window.innerHeight;
            $('.gridStyle').height(scope.height - 100);
        }

        angular.element($window).bind('resize', function() {
            scope.$apply(function() {
                applyHeight();
            });
        });

        applyHeight();
    };
});

これは、ブラウザ ウィンドウのサイズを変更するときにはうまく機能しますが、サイトが初めて読み込まれるときにはスタイルが適用されません。高さを初期化するコードはどこに配置できますか?

ベストアンサー1

私自身も同じ問題の解決策を探していたときに、あなたの投稿に出会いました。いくつかの投稿に基づいたディレクティブを使用して、次の解決策をまとめました。ここで試すことができます (ブラウザ ウィンドウのサイズを変更してみてください)。http://jsfiddle.net/zbjLh/2/

ビュー:

<div ng-app="miniapp" ng-controller="AppController" ng-style="style()" resize>
    window.height: {{windowHeight}} <br />
    window.width: {{windowWidth}} <br />
</div>

コントローラ:

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

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

app.directive('resize', function ($window) {
    return function (scope, element) {
        var w = angular.element($window);
        scope.getWindowDimensions = function () {
            return { 'h': w.height(), 'w': w.width() };
        };
        scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
            scope.windowHeight = newValue.h;
            scope.windowWidth = newValue.w;

            scope.style = function () {
                return { 
                    'height': (newValue.h - 100) + 'px',
                    'width': (newValue.w - 100) + 'px' 
                };
            };

        }, true);

        w.bind('resize', function () {
            scope.$apply();
        });
    }
})

ちなみに、私はもともとコントローラーで動作させていました(http://jsfiddle.net/zbjLh/) でしたが、その後読んでみると、これは Angular の観点からはクールではないことがわかったので、ディレクティブを使用するように変換しました。

重要なのは、truegetWindowDimensions が返すオブジェクトの等価性を比較するための 'watch' 関数の末尾のフラグに注意してください (オブジェクトを使用していない場合は削除するか、false に変更します)。

おすすめ記事