codeman
codeman

Reputation: 47

angularJS observing array length with $watch method

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();

}

Upvotes: 0

Views: 649

Answers (2)

charlietfl
charlietfl

Reputation: 171690

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

Upvotes: 2

Maxim Shoustin
Maxim Shoustin

Reputation: 77910

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

Upvotes: 3

Related Questions