Search code examples
jsonangularjsajaxangular-filters

AngularJS $http and filters


I have a JSON file, which contains:

{
  "/default.aspx": "headerBg",
  "/about.aspx": "aboutBg",
  "/contact.aspx": "contactBg",
  "/registration.aspx": "regBg",
  "/clients.aspx": "clientsBg",
  "/onlinesessions.aspx": "bg-white-box",
  "/ondemamdsessions.aspx": "bg-grey"
}

Now I am reading this json file using $http, but I want to add a filter in below fashion:

Using window.location.pathname, I am reading path of the current page, suppose the current page is /about.aspx

Then I want to add a filter in $http response by which I want to read only aboutBg.

The code I wrote can retrieve all the values, but unable to filter that. Please help.


Solution

  • User this function where you receive the response.

    function getPageBgClass(currentPage, responseData) {
    
        if (responseData.hasOwnProperty(currentPage))
           return responseData[currentPage]
        else
           return "none"
    }
    

    Here is how it should be used in your promise then function

    function(response) {
    
         var bg = getPageBgClass(window.location.pathname, response.data);
    
         //Your code here ...
    }