AngularJS - filter for undefined properties in ng-repeat?

前端 未结 4 949
天涯浪人
天涯浪人 2021-02-05 00:43

For my AngularJS project (v1.2.3), I have a list of routes and am trying to build a navigation bar from the object. What I want to do is display any object with an undefined

4条回答
  •  南笙
    南笙 (楼主)
    2021-02-05 00:54

    Edit

    I just reread the question, and this is not the answer you are looking for. I will leave it here for documentation purposes, but I do not think there is a way to get the functionality you desire without either building a custom filter or using a custom filter function.

    To expand on why looking for undefined will not work with the default filter we take a look at this code from the AngularJS filter implementation.

    switch (typeof expression) {
      ...
      case "object":
        // jshint +W086
        for (var key in expression) {
          (function(path) {
            if (typeof expression[path] == 'undefined') return;
            predicates.push(function(value) {
              return search(path == '$' ? value : getter(value, path), expression[path]);
            });
          })(key);
        }
        break;
      ...
    }
    

    If a value for the filter object's property is undefined, no predicate function is added to the predicates array. In your case you are setting the value of the isRight property to undefined (your filter expression is {isRight:undefined}).

    Original Answer

    You can always use a predicate function to create arbitrary filters (documentation).

    A predicate function can be used to write arbitrary filters. The function is called for each element of array. The final result is an array of those elements that the predicate returned true for.

    In your controller create a method to pick the items you want

    $scope.isRightUndefined = function(item) {
      return item.isRight === undefined;
    }
    

    and change your repeat to be

提交回复
热议问题