如何在angular.js指令中访问作用域变量

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

本文关键字:访问 作用域 变量 指令 js angular      更新时间:2023-09-26

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

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也不起作用。我该怎么做呢?有什么简单快捷的方法吗?

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

您可以将任意数量的作用域成员直接传递给过滤器(以冒号分隔)…

myfilter:filterTerm:isContentFilterOn

更新过滤器方法签名…

function(postList, term, isContentFilterOn) {

你想怎么用就怎么用……

 if (isContentFilterOn) { 

哦,别忘了,你可能需要在作用域中将isContentFilterOn定义为false,这样它就可以立即用于过滤器…

$scope.isContentFilterOn = false;

更新普朗克在这里显示我的意思…

http://plnkr.co/edit/vPTBws0JBpwvKY0ywCPC?p =预览