2016-08-15 33 views
1

如何過濾一個屬性的數組,取決於URL參數定義爲true或不是?我嘗試了以下,但:「錯誤:$位置未定義」。儘管如此,我已將它提供給模板的控制器。如何根據url參數過濾數組

的javascript:

app.filter('myFilter', function() { 

    return function(items) { 
     return items.filter(function(element){ 
      var ext = ($location.search().ext == "true"); // Check if url contains ?ext=true 
      if (ext == true){ 
       if (externallyAvailable == 'true') { 
        return true; 
       } 
      } 
      else{ 
       return true; 
      } 
     }); 
    } 
}); 

app.controller('tilesController', ['$scope', '$http', '$sce', '$location', '$filter', function($scope, $http, $sce, $location, $filter) { 
    /* some controller logic */ 
} 

模板:

<li ng-repeat="tile in list.tiles | myFilter" class="tile-wrapper"> 
    <!-- content --> 
</li> 

我還發現,我的解決方案,它是否會工作,需要更多的線比我期望的,所以其他的建議都歡迎。

回答

1

您還需要在過濾器中注入$ location Provider。正如你還沒有這樣做,這就是爲什麼它向你展示未定義的錯誤。嘗試這樣的

app.filter('myFilter', function($location) { 

    return function(items) { 
     return items.filter(function(element, $location){ 
      var ext = ($location.search().ext == "true"); // Check if url contains ?ext=true 
      if (ext == true){ 
       if (externallyAvailable == 'true') { 
        return true; 
       } 
      } 
      else{ 
       return true; 
      } 
     }); 
    } 
}); 
+0

而且顯然沒有必要注入$位置到控制器。謝謝! – kslstn

+0

不客氣。樂於幫助 :) –

0

你試圖使用$location服務檢查字符串(不管它是一個UL的字符串)

下面是一個未經考驗的開始你一起工作:

app.filter('containsExtParam', function() { 

    return function(items) { 
     return items.filter(function(element){ 
      return element.indexOf('?ext=true') !== -1; 
     }); 
    } 
});