【问题标题】:How to add dynamic column in ng-repeat filter如何在 ng-repeat 过滤器中添加动态列
【发布时间】:2019-07-12 16:26:48
【问题描述】:

是否可以在ng-repeat过滤器中添加动态列filter:{'Is'+dType.Name:true}

<option ng-repeat="option in mainCtrl.Maps | filter:{'Is'+dType.Name:true}" ng-value="option.Id">{{option.Name}}</option>

【问题讨论】:

    标签: html angularjs angularjs-ng-repeat


    【解决方案1】:

    不,Angular 会抛出错误。但是您可以改用一个函数,该函数可以与动态属性一起使用,例如:

    <option ng-repeat="option in mainCtrl.Maps | filter:filterFn" ng-value="option.Id">{{option.Name}}</option>
    

    在控制器中:

    $scope.filterFn = function(option) {
      var propName = 'Is' + $scope.dType.Name; // assuming that dType is somewhere in the scope
      return option[propName] === true; // this replaces the shorthand filter in the ng-repeat
    }
    

    编辑(由于原始问题中不包含其他详细信息):

    如果您想将附加参数传递给您的过滤器函数,您可以使用我在以下 SO 答案中找到的内容:How to use parameters within the filter in AngularJS?

    适应你的情况:

    <option ng-repeat="option in mainCtrl.Maps | filter:filterFn(dType)" ng-value="option.Id">{{option.Name}}</option>
    

    在控制器中:

    $scope.filterFn = function(dType) {
      return function (option) {
        var propName = 'Is' + dType.Name; // dType is passed as parameter
        return option[propName] === true; 
      };
    };
    

    简而言之,您的过滤器函数必须返回一个具有 Angular 所期望的签名的函数(具有一个参数的函数:ng-repeat 的元素),但由于包装它还可以处理其他参数。

    【讨论】:

    • dType.Nameng-repeat 内。因为我需要通过dType.Name,所以我尝试了这样filter:{mainCtrl.getDType(dType.Name):true}。在函数中添加===true 不会对其进行过滤。
    • @klent 我添加了一个选项,应该涵盖你的情况。
    • 我没有在函数中添加option,所以我之前尝试的时候它不起作用。它现在过滤。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 2016-06-16
    • 2014-04-14
    • 2015-06-21
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多