如何从 angular.js 中的指令中访问范围变量?

How to access scope variables from within a directive in angular.js?

我定义了自己的自定义过滤器,以便在 angular.js 网络应用程序中搜索帖子:

app.filter('myfilter', function() {
return function(postList, term) {
  var out = [];

  if(!postList) return out;    
  if(!term) return postList;

  var i;
  for(i = 0; i < postList.length; i++){
    if(postList[i].title.indexOf(term) >=0){
        out.push(postList[i]);
    }

    if($scope.isContentFilterOn.checked){
        if(postList[i].text.indexOf(term) >=0){
                out.push(postList[i]);
            }
        }
    }
    }
    return out;
}
});

当然上面的方法不起作用,因为我不能访问作用域变量,简单地传递 $scope 也不起作用。请问有什么简单快捷的方法吗?

编辑:来源http://plnkr.co/edit/G9BFBTaKdUmki8MJegrn?p=catalogue

您可以将任意数量的范围成员直接传递给过滤器(以冒号分隔)...

myfilter:filterTerm:isContentFilterOn

更新过滤器方法签名...

function(postList, term, isContentFilterOn) {

然后随心所欲地使用它...

 if (isContentFilterOn) { 

哦,别忘了您可能需要首先在范围内将 isContentFilterOn 定义为 false,以便过滤器可以立即使用它...

$scope.isContentFilterOn = false;

在此处更新了 Plunker 以说明我的意思...

http://plnkr.co/edit/vPTBws0JBpwvKY0ywCPC?p=preview