Search code examples
angularjsangularjs-scopeangularjs-watch

How to update scope var from Math expression and another scope var?


Not sure if I made myself clear on my question but what I really want is to update the min-width with ng-style for each <li> within an ng-repeat to equal the percentage of 100 / array.length.

My first solution is simply:

<li ng-style="{'min-width': (100 / array.length) + '%'}">

This works, but I don't like the Math expression in the view, I'd rather have it in the controller. Something in the lines of:

$scope.percentage = (100 / $scope.array.length) + '%'

<li ng-style="{'min-width': percentage}"

The problem with this approach is that when the array contents change, percentage is not changed. I could add a $watchCollection to array and update percentage there, but it doesn't feel right, like I'm missing a better approach. Am I?

If not, which solution do you prefer? Math expression in the view, or $watchCollection?


Solution

  • You should define percentage as a function.

    See here:

    http://jsfiddle.net/waxolunist/5bnhj4vt/6/

    HTML:

    <div ng-app="app">
        <div ng-controller="AController">
            <ul>
                <li class="red" ng-repeat="item in items" ng-style="{'width': percentage()}">{{item}}</li>
            </ul>
    
        <button ng-click="addItem()">addItem</button>
        </div>
    
    
    </div>
    

    JS:

    var app = angular.module('app', []);
    
    app.controller('AController', function($scope) {
    
        $scope.items = [1,2,3,4,5,6];
    
        $scope.percentage = function() {
            return 100/$scope.items.length + '%';
        }
    
        $scope.addItem = function() {
            $scope.items.push($scope.items.length + 1);
        }
    });