2015-07-12 55 views
2

我有一個表,其默認寬度是一個特定的值,比如父div的80%。該表最初是隱藏使用 'NG-如果' 直到某個AJAX通話結束如下:Angularjs/jQuery:在ajax調用完成後更改表格的寬度。

HTML:

<div ng-if="!loading"> 
    <table id="table-stable"> 
     <thead> 
      //columns 
     </thead> 
     <tbody> 
      <tr ng-repeat="data in tableData"> 
       //rows 
      </tr> 
     </tbody> 
    </table> 
</div> 

AngularJS控制器:

$scope.loading = true; 
someFactory.getData().then(function(data) { 
    $scope.loading = false; 
    $scope.tableData = data; 
    //now need to write code to change table's width dependant on data. 
}) 

正如在控制器中所解釋的,根據從工廠提取的數據,我需要更改表格的寬度。

問題在於表中的2列根據取數據中的值沒有顯示,所以如果這些列沒有顯示,那麼我需要縮小表的寬度。

目前,在ajax調用完成後編寫jQuery不起作用。上面指定的控制器的代碼:

$scope.loading = true; 
    someFactory.getData().then(function(data) { 
     $scope.loading = false; 
     $scope.tableData = data; 
     $('#table-stable').attr('width', '100px'); //not working. 
    }) 

我的猜測是該表尚未完全呈現?那麼,我在這裏黑暗中拍攝。我如何處理這個問題?

回答

1

如果你可以改變一個變量,表示是否這些列應根據數據顯示,你可以使用ng-class,你的元素的類將實時更新。

例如,給自己這些CSS類:

.wide-table { 
    width: 80%; 
} 

.narrow-table { 
    width: 100px; 
} 

然後在視圖中,是這樣的:

<table id="table-stable" ng-class="{'narrow-table': columnsHidden, 'wide-table': !columnsHidden}"> 

這裏有一個fiddle

更新:由於您使用的ng-if,你可能只使用一個香草類屬性,like so內的表達。

+0

我認爲這是最好的方法。謝謝。 –

0

那麼,事實證明我是在做jQuery錯誤。有人在評論中指出了這一點(雖然現在刪除)

以前的代碼:

$('#table-stable').attr('width', '100px'); 

正確的代碼:

$('#table-stable').css('width', '100px'); 
+0

是......正好。另一件事你不應該對你的控制器做UI的責任。更好的是,如果在視圖內做那個伎倆;) –

+0

謝謝,請記住:) –

+0

問題不在這裏,'attr'屬性工作:[demo](https://jsfiddle.net/xp2255r4/) –

2

我的猜測是表格還沒有完全呈現?

你說得對。使用ng-if會使事情複雜化,請使用ng-showng-hide代替。此外,jQuery在這裏是令人反感的,當它對Angular非常有用時,沒有太多場景。你可以做

<div ng-show="!loading"> 
    <table id="table-stable" ng-style="lengthyTable && { width: '100px' }"> 
    ... 
+0

感謝您的指點! –