简体   繁体   中英

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

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">

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"    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM