[英]How to access scope variables from within a directive in angular.js?
我已經定義了自己的自定義過濾器,以便在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
也行不通。 我該怎么做-是否有任何簡單快捷的方法?
您可以將任意數量的作用域成員直接傳遞到過濾器(以冒號分隔)...
myfilter:filterTerm:isContentFilterOn
更新過濾器方法簽名...
function(postList, term, isContentFilterOn) {
然后隨便使用它...
if (isContentFilterOn) {
哦,別忘了,您可能需要在范圍中將isContentFilterOn定義為false,因此它可以立即用於過濾器...
$scope.isContentFilterOn = false;
在這里更新了Plunker以顯示我的意思...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.