Search code examples
javascriptangularjsangularjs-ng-clickangularjs-ng-class

How to combine ng-class checks and ng-click comparisons?


I have an ng-repeat where the first item needs to have the class selected, as well as clicking on each item then changes the selection.

<li ng-repeat="ticker in tickers"
    data-ng-class="{'selected':$first}"
    ng-click="selectTicker(ticker.ticker)">{{ticker.ticker}}</li>

^ This works to have the first item have the class of selected by default.

<li ng-repeat="ticker in tickers"
    data-ng-click="toggleTicker.item = $index"
    data-ng-class="{'selected':toggleTicker.item == $index}"
    ng-click="selectTicker(ticker.ticker)">{{ticker.ticker}}</li>

^ Thanks to this question. The above works to add the class of selected based on click, but the first item is no longer selected by default.

My question is how to combine both? I've tried the following which did not work:

data-ng-class="{'selected':$first && toggleObject.item == $index}"

My controller:

var vs = $scope;

ApiFactory.getWatchList().then(function(data) {
    vs.tickers = data.data.tickers;
    vs.toggleTicker = {item: -1};
    vs.toggleTicker.item = vs.tickers[0];
    vs.loadingDone = true;
    console.log(vs.tickers[0]);
});

Solution

  • You are initializing item to the object at index 0 in your controller, but everywhere else it seems to be a number. If you just want to use the index (as your click sets it to the number), then try this:

    var vs = $scope;
    
    ApiFactory.getWatchList().then(function(data) {
        vs.tickers = data.data.tickers;
        vs.toggleTicker = {item: 0}; // set index 0 as the selected index
        vs.loadingDone = true;
        //console.log(vs.tickers[0]); // what if there are no items?
    });
    

    html:

    <li ng-repeat="ticker in tickers"
        data-ng-click="toggleTicker.item = $index"
        data-ng-class="{'selected':toggleTicker.item == $index}"
        {{ticker.ticker}}
    </li>
    

    Using $first is bad because the same item will always be the first one (unless you re-order them). Using ng-click and data-ng-click is bad because they are essentially identical, maybe only one will actually get called?