ng-if在ng-repeat中始终评估为true

时间:2019-05-16 10:17:53

标签: javascript html angularjs

我正在循环对象数组,我想根据数组中每个项目的字段值显示一些内容。为此,我在数组中进行了ng-repeat迭代,并通过ng-if评估了我当前的项目值是否合适。

出于某种原因,ng-if似乎总是被评估为true(或根本没有被评估?)

edit.html

<div data-ng-app='myApp' data-ng-controller='myCtrl'>

  <div>
    <div ng-repeat="legalRemedy in legalRemedies">
      <div ng-if="legalRemedy.erased === false">
        Only valid stuff here
      </div>
    </div>
  </div>

</div>

controller.js

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

  $scope.bulletin.legalRemedies = [{
    "erased": true // invalid stuff
  }];

});

这是jsfiddle(由于被擦除的属性为true,因此不应显示任何数据) https://jsfiddle.net/vtcLpzmx/2/

这可能很愚蠢,但我找不到原因,这正在杀死我

3 个答案:

答案 0 :(得分:0)

您的代码运行正常。只是在您的jsfiddle中,我认为您错过了添加角度脚本的过程。这样就不会把小提琴当作有角度的应用。

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
  $scope.bulletin = {};
  $scope.bulletin.legalRemedies = [{"erased" : true}]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div data-ng-app='myApp' data-ng-controller='myCtrl'>

  <div>
  
    <div ng-repeat="legalRemedy in bulletin.legalRemedies">
      <div ng-if="!legalRemedy.erased">
        Only valid stuff here
      </div>
    </div>
  </div>

</div>

答案 1 :(得分:0)

$ scope.bulletin.legalRemedies导致错误,因为未定义$ scope.bulletin。首先,您需要为对象声明$ scope.bulletin。

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div data-ng-app='myApp' data-ng-controller='myCtrl'>
  <div>
    <div ng-repeat="legalRemedy in bulletin.legalRemedies">
      <div ng-if="!legalRemedy.erased">
        Only valid stuff here
      </div>
    </div>
  </div>

</div>
<script>
    var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
  $scope.bulletin = {
    legalRemedies : [{
      "erased": true // invalid stuff
    }
    ]
  }

});
</script>

</body>
</html>

答案 2 :(得分:0)

尝试以下解决方案。更改了$scope.bulletin变量。

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
  $scope.bulletin = { legalRemedies : [{
    "erased": true // invalid stuff
  },{
    "erased": false 
  }] };

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>


<div ng-app='myApp' ng-controller='myCtrl'>
    
  <div>
    <div ng-repeat="legalRemedy in bulletin.legalRemedies">
      {{$index}} - {{ legalRemedy }}
      <div ng-if="!legalRemedy.erased">
        Only valid stuff here
      </div>
    </div>
  </div> 
    
    
</div>