2013-11-02 38 views
0

我有這樣的工作代碼(下面),它的功能和做它應該很好,但它不是最佳的,可以請幫助我用$ watch方法重寫它?我曾多次嘗試,但它沒有work.here是我的線指的這一個: angularjs angular doesn't read the length of an array

http://jsfiddle.net/Tb9j5/8/

function dialogWindows($scope) { 
    $scope.alpeic = []; 
    $scope.compute=function() 
    { 
     $scope.alpeic.push(1); 
     $scope.records = [ 
     {id:0, 
     link:$scope.alpeic.length > 5 ? "alpeic.html" : "", 
     className:$scope.alpeic.length > 5 ? "special" : "normal", 
     item:"This is item A"}, 
     {id:1, 
     link:$scope.alpeic.length > 5 ? "alpeic.html" : "", 
     className:$scope.alpeic.length > 5 ? "special" : "normal", 
     item:"This is item B"}]; 
    } 

    $scope.compute(); 

} 

回答

3

我會用ng-style混合ng-class

參考:

  • ng-class - 使用當組CSS樣式是靜態/事先已知的
  • ng-style - 使用時不能定義CSS類,因爲樣式值可能會動態變化。

例如:

<div ng-repeat="record in records"> 
     <a href="{{record.link}}"> 
      <div 
       ng-style="myStyle()" 
       ng-class="{true: 'special', false: 'normal'}[alpeic.length > 5]" 
      >{{record.item}} 
      </div> 
     </a> 
    </div> 

和控制器:

$scope.myStyle = function() { 
    var style = {}; 

    if ($scope.alpeic.length > 5) { 
     style = {"font-size": 30 + 'px'}; 
    } else { 
     style = {"font-size": ($scope.alpeic.length + 12) + 'px'}; 
    } 
    return style; 
}; 

演示Fiddle

+0

有趣的可以使用2種不同的方法來評估'NG-class' JS表達......我從來沒有見過你用過的語法...很酷 – charlietfl

2

ng-class將評估一些javascript,includi納克length和內使用的任何變量範圍屬性....例如:

<div ng-class="{'normal':alpeic.length <=5, 'special':alpeic.length >5 }" > 

創建一個對象,其中關鍵是類名和值基於範圍或者是一個布爾一個簡單的範圍是可變的js表達。

布爾變量可以用!也納克級內

DEMO