angularjs:ng-if条件显示ngrepeat条件是否失败?

时间:2017-02-01 16:15:32

标签: javascript angularjs arrays

ng-if使用ng-repeat数组和非数组。

如果条件为真,它对数组和非数组工作正常(显示div),但如果条件为false,它仍然显示 div 。如果条件为真,我只需要显示 divs

下面我提到了html。

<ul class="dropdown-menu">
   <li class="notify-header col-sm-12 text-center bgf9">Notifications</li>
   <li class="notify-values" ng-if="Array.isArray(getnotifications.notifications)">
      <li ng-repeat="notification in getnotifications.notifications">
         <p class="col-sm-9 {{notification.getreviewer}}">

            <span class="nvalue-head">{{notification.name}}</span><br>
            <span><b>{{notification.user_role}}:</b> {{notification.raisedBy}}</span>
            <span>{{notification.message}}</span>
         </p>
         <p class="col-sm-3 online-status text-right"> <time am-time-ago="notification.updateTime" title="{{ notification.updateTime | amDateFormat: 'dddd, MMMM Do YYYY, h:mm a' }}"></time></p>
      </li>
   </li>
   <li class="notify-values" ng-if="!Array.isArray(getnotifications.notifications)">
      <p class="col-sm-9 {{getnotifications.notifications.getreviewer}}">

         <span class="nvalue-head">{{getnotifications.notifications.name}}</span>
         <span><b>{{getnotifications.notifications.user_role}}:</b> {{getnotifications.notifications.raisedBy}}</span>
         <span>{{getnotifications.notifications.message}}</span>
      </p>
      <p class="col-sm-3 online-status text-right"> <time am-time-ago="getnotifications.notifications.updateTime" title="{{ getnotifications.notifications.updateTime | amDateFormat: 'dddd, MMMM Do YYYY, h:mm a' }}"></time></p>

   </li>
</ul>

在控制器中,

$scope.getnotifications=$localStorage.getnotification;

非数组的JSON:

{
  "NotificationList": {
    "notifications": {
      "id": 2945,
      "message": "Conversation Reviewing",
      "name": "dfgdfg",
      "raisedBy": "abcde",
      "status": 0,
      "updateTime": "2017-02-01 17:41:26.0",
      "user_role": "Creator"
    },
    "unread": 0
  }
}

数组的JSON:

{
  "NotificationList": {
    "notifications": [
      {
        "id": 2946,
        "message": "Conversation Reviewing",
        "name": "sdf",
        "raisedBy": "creator",
        "status": 0,
        "updateTime": "2017-02-01 21:00:43.0",
        "user_role": "Creator"
      },
      {
        "id": 2935,
        "message": "Conversation Reviewing",
        "name": "new testing conversation",
        "raisedBy": "creator"
      }
    ],
    "unread": 0
  }
}

1 个答案:

答案 0 :(得分:0)

您应该将ng-if中的条件移动到控制器

样本测试用例

视图

<div ng-app="Test">
 <ul ng-controller="test">
   <div ng-if="isArray(days)">
      <li ng-repeat="day in days">
        {{day}}
      </li>
   </div>
 </ul>
</div>

控制器

angular.module("Test", [])
  .controller("test", function($scope){
     $scope.days=[
  "Sunday",
  "Monday",
  "Tuesday"]

  $scope.isArray= function(d){
   if(Array.isArray(d))
    return true;
  return false;
  }
})

Sample Working Pen