Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-class not working. Where did I do wrong?

I know there are many problems here listed like this. but I can't pinpoint where I did wrong..

<li ng-repeat="item in type.sub | orderBy:y" ng-click="openpic($parent.$index, $index)" ng-class="{ 'active': $parent.$index + ':' + $index == current }">

we have $scope.current variable, and a nested menu with numbering id like 1:2, 1:3, 1:4, 2:1, 2:2, 2:3 and so on.

Goal is very simple. I need to make this <li> active, if the $parent.$index:$index is equal to $scope.current. ID is set whenever openpic($parent.$index, $index) triggered. We have li.active class in css.

So, can someone please show me, what's missing in that code?

TRY 1:

Tried:

<li ng-repeat="item in type.sub | orderBy:y" ng-click="openpic($parent.$index, $index)" ng-class="{ 'active': $parent.$index + ':' + $index == $parent.current }">

Still not working.

TRY 2

I have something like this:

ng-class="{{ $parent.$index + ':' + $index == $parent.current && 'active' || '' }}"

and it shows as ng-class="active" but class attribute did not updated.

TRY 3

ng-class="{{ $parent.$index + ':' + $index == $parent.current && 'highlight' || '' }}"

it shows ng-class='highlight", but class still shows class="ng-binding ng-scope"

TRY 4

ng-class="isActive($parent.$index,$index)"

It solves the problem, but it seems a little bit overkill for a simple switch function. Any more ideas?

TRY 5

As per major-mann code suggestion that works at TRY 4, I made these adjustment, and surprisingly, it works.

ng-class="$parent.$index + ':' + $index == $parent.current && 'active' || ''"

That one works. Removed all braces completely ????

like image 254
Magician Avatar asked Oct 20 '22 03:10

Magician


1 Answers

First of all make {{$parent.$index:$index}} to make sure to get the right data (I just never met such a method to data access) ;
If it's ok, then try use:

ng-class="$parent.$index:$index === current ? 'active' : ''"

Or (best way) use function for this:

ng-class="someFn($parent.$index)"
$scope.someFn = function(index){
    //index, index:index, index[n] or something else;
    return index === $scope.current ? 'active' : '';
};

Update:
If You want get access to parent ng-repeat, better use

<...  ng-repeat="(index1, data1) in firstData">
    <...  ng-repeat="(index2, data2) in secondData">
        <... ng-something="index1 operator index2 or function(index1, index2)">

I hope, it will help;

like image 114
user3335966 Avatar answered Nov 03 '22 00:11

user3335966