0

I have this piece of working code (below)which functions and does what it should nicely however it is not optimal, could please help me with rewriting it with the $watch method ? I had several attempts but it didnt work.here is my thread refering to this one: 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();

}
Community
  • 1
  • 1
codeman
  • 47
  • 1
  • 3
  • 9

2 Answers2

3

I would use ng-style mixed with ng-class.

reference:

  • ng-class - use when the set of CSS styles is static/known ahead of time
  • ng-style - use when you can't define a CSS class because the style values may change dynamically.

For example:

 <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>

and in controller:

  $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;
};

Demo Fiddle

Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
  • interesting can use 2 different approaches to evaluate js expression in `ng-class` ...I've never seen syntax you used... quite cool – charlietfl Nov 02 '13 at 23:46
2

ng-class will evaluate some javascript , including length and any variables used within are scope properties.... for example:

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

Create an object where key is class name and value is js expression based on scope or a simple scope variable that is a boolean.

Boolean variable can use ! also within ng-class

DEMO

charlietfl
  • 170,828
  • 13
  • 121
  • 150