Search code examples
javascriptangularjsangular-ng-if

AngularJS: ngIf in array of objects with different properties


I have some issue with ngIf directive. I tried a lot of ways to resolve it, but unfortunately failed.

I have an array of objects with different properties. Something like this:

    object = [
    {
        name: "1",
        isNumber: true,
    },
    {
        name: "2",
        isNumber: true,
    },
    {
        name: "3",
        isNumber: true,
    },
    {
        name: "4",
        isNumber: true,
    },
    {
        name: "5",
        isNumber: true,
    },
    {
        name: "#",
        isNumber: false,
    },
    {
        name: "*",
        isNumber: false,
    }

I need to use ngIf on the last object with true value of isNumber property. I don't know how much objects with isNumber on true will be in my array. It can be 7 or 82. Nobody knows. Also objects with isNumber on false won't be always in my array. Sometimes array will be have only objects with isNumber on true and no objects with isNumber on false.

How can i achieve this using ngIf?

Thanks in advance.

UPDATE:

I have something like this:

1, 2, 3, 4, 5, 6, 7, *, #.

And I don't want to have "Down" button on last element with true value of isNumber property (7 in this case). Because if user moves it down, I'll have this:

1, 2, 3, 4, 5, 6, *, 7, #.

And it will be wrong logic.

So, I need to use ngIf, so that I could disable this button on that element. But sometimes I can have smth like this (without extra symbols):

1, 2, 3, 4, 5.

And in this situation I don't need "Down" button on last element too. Because it's impossible to move last element down.


Solution

  • If you're trying to find if it's the last element AND if isNumber is set to true, you can use this:

    <span ng-repeat="item in items" ng-if="item.isNumber && $last">

    $last is a special variable defined through ngRepeat, located here. Since ngIf accepts a boolean statement, you can use both the logical && and || operators.

    Edit: if you're not iterating over it with ngRepeat and you just want to select the last element, you can do something like this to select the last one, then use ngIf to display it if isNumber is set to true:

    <span ng-bind="list[list.length - 1]" ng-if="list.isNumber">

    Edit 2: Could you "peek" at the next element and see if the next isNumber is set to false? Like this:

    <span ng-repeat="...">
       <span ng-if="!list[$index + 1].isNumber"></span>
    </span>
    

    Like $last, I'm using a special variable called $index to go to the next element in the ngRepeat. (not sure if Angular automatically checks out-of-bounds errors, or if it'll throw an error)