如何根据AngularJS中的范围过滤数据?

时间:2016-02-24 23:44:52

标签: angularjs angularjs-directive angular-filters

我有以下简化的plunker来证明我的问题:

HTML:

<my-directive ng-repeat="question in questions | filter:{show:true}" data-question="question">    </my-directive>

指令:

app.controller('MainCtrl', function($scope) {
  $scope.questions = [
    {qid:'1', show: true, text:'what is?'},
    {qid:'2', show: false, text:'who is?'},
    {qid:'3', show: true, text:'where is?'}
 ];
});

app.directive('myDirective', function() {
return {
  link: function(scope){
    scope.getShow = function(){
      // some logic to determine show
      // for simlicity , always return true so all questiosn show
      return true;
    };
  },
  restrict: "E",
  scope: {
    question: "="
  },
  template: '<h1>{{question.text}}</h1>'
  };
});

目前,过滤器的工作原理是来自原始数据模型的“show”值。但我试图从原始数据中清除它,并使其工作基于问题范围级别定义的getShow()逻辑。

通常,我无法找到基于作用域上的字段或函数而不是数据模型进行过滤的方法,并且无法找到如何完成此操作的示例。

1 个答案:

答案 0 :(得分:2)

ng-repeat内,只需设置ng-show等于getShow()函数,然后传递迭代问题。

获取getShow()以检查show是true还是false,并返回该值。

app.js

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {
  $scope.questions = [
    {qid:'1', show: true, text:'what is?'},
    {qid:'2', show: false, text:'who is?'},
    {qid:'3', show: true, text:'where is?'}
  ];
});

app.directive('myDirective', function() {
  return {
    link: function(scope){
      scope.getShow = function(question){
        // some logic to determine show
        // for simlicity , always return true so all questiosn show
        return question.show
      };
    },
    restrict: "E",
    scope: {
      question: "="
    },
    template: '<h1>{{question.text}}</h1>'
  };
});

index.html

<my-directive ng-repeat="question in questions" ng-show="getShow(question)" data-question="question">

当然,the editable plunker to show.