2

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

1
  • You need not explicitly give interpolate braces to loggedInUser. $compile does that for the ng-if directive Commented Sep 22, 2015 at 13:54

2 Answers 2

8

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">
Sign up to request clarification or add additional context in comments.

3 Comments

@PratapA.K You can accept as an answer for further usage
Sure will do that!! I have one more doubt, What if $scope of loggedOnUser and users array are different???
You must be using service or factory in this case you can reference the literals to that factory or service.
3

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"    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.