nima_santur
nima_santur

Reputation: 43

ng-if not working with ng-repeat

This should be a simple issue, but I don't understand what's happening. Basically I'm passing an object to a function call in my controller with ng-if withing an ng-repeat. However my function doesn't see the param passed to it. It says undefined.

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

app.controller('NewFormController', ['$scope', '$log',
            function($scope, $log) {
              
     $scope.meta = {
      "GRANT": {
        "VALUE": "2",
        "DEFAULT": "1",
        "RANGE": "1:4",
        "TYPE": "INTEGER",
        "DESCRIPTION": "Some description"
      }
    };

    $scope.testing = function(x) {
        $log.debug('X is: ' + x);
        if (x == "1:4") {
          return true;
        } else {
          return false;
        }
    };
    
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<tr ng-repeat="(param,value) in meta">
  <td>{{param}}</td>
  <td>{{value.DESCRIPTION}}</td>
  <span ng-if="testing(value.RANGE)">
                  <td><input type="text" class="form-control" value="{{value.DEFAULT}}"></td>
              </span>
</tr>

Why does the console print 'undefine' ? And why does the function get call so many times? I only have one key, shouldn't ng-repeat just loop only once?

enter image description here

Now if I instead of "value.RANGE" pass some string to the function, the string will be read/printed correctly...

Upvotes: 0

Views: 1586

Answers (2)

ajmajmajma
ajmajmajma

Reputation: 14226

It's because you have invalid html - check out this example - http://jsfiddle.net/HB7LU/16355/

I just modified your table code to look like this

<table>
    <tr ng-repeat="(param,value) in meta">
        <td>{{param}}</td>
        <td>{{value.DESCRIPTION}}</td>
        <td ng-if="testing(value.RANGE)">
            <input type="text" class="form-control" value="{{value.DEFAULT}}">
        </td>
    </tr>
</table>

And it works :).

Upvotes: 2

charlietfl
charlietfl

Reputation: 171698

If you use valid html it works fine

<tr ng-repeat="(param,value) in meta">
  <td>{{param}}</td>
  <td>{{value.DESCRIPTION}}</td>

  <td ng-if="testing(value.RANGE)">
    <input type="text" class="form-control" value="{{value.DEFAULT}}">
  </td>

</tr>

<span> is not a valid child of <tr> so browser is likely moving it outside of the table and therefore outside of the ng-repeat child scope. Then when angular runs that function it is in different scope

working version

Upvotes: 1

Related Questions