Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-if with angular expression

View:

<html ng-app="myApp">
....
  <body>

    <div ng-controller="myCtrl">

      <p>Current user {{loggedOnUser}}</p>

      <div ng-if="user.name == {{loggedOnUser}}" ng-repeat="user in users">
        <p>Should display</p>
      </div>

    </div>

  </body>

</html>

Controller:

angular.module("myApp", [])
  .controller("myCtrl", function($scope){
    $scope.loggedOnUser = "xxx"; // for testing purpose
    $scope.users = [
      {
        name : "xxx",
        age: "25"
      },
      {
        name : "yyy",
        age: "26"
      }
    ];
 });

How to use ng-if with angularJS expression or is there any other way to achieve this?? I want to show that div if my loggedOnUser is equal to user.name

Thanks in advance

like image 900
Pratap A.K Avatar asked Jun 10 '26 17:06

Pratap A.K


2 Answers

It should be

ng-if="user.name == loggedOnUser"

instead of

ng-if="user.name == {{loggedOnUser}}"

You can user filters if you want to. But I suggest you to not trust on filters in your case. Please see below snippet, it will work in your above scenario.

<div ng-repeat="user in users | filter:name:loggedOnUser">
like image 108
Vineet Avatar answered Jun 12 '26 10:06

Vineet


The condition for ng-if is an angular expression itself.

<ANY
    ng-if="expression">
    ...
</ANY>

therefore something like:

ng-if="someVal"

will match for $scope.someVal and not against the string "someVal"
so in your case it should be:

ng-if="user.name == loggedOnUser"    
like image 42
Gaurav Gupta Avatar answered Jun 12 '26 10:06

Gaurav Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!