Set factory variable from state

I am using factories to get feed data for different categories in wordpress using the Rest-API and I am wondering if I am making a complete mess of it.

I have around 13 different categories that I am making just a basic call to that look like this:

Read More
.factory('Articles1', function ($http) {
    var articles1 = [];
       storageKey = "articles1";

    function _getCache() {
        var cache = localStorage.getItem(storageKey );
        if (cache)
            articles = angular.fromJson(cache);
    }


    return {
        all: function () {
            return $http.get("http://www.example.com/wp-json/posts?filter[category_name]=category1").then(function (response) {
                articles1 = response.data;
                console.log(response.data);
                return articles1;
            });
        },

        get: function (articleId) {
            if (!articles1.length) 
                _getCache();
            for (var i = 0; i < articles1.length; i++) {
                if (parseInt(articles1[i].ID) === parseInt(article1Id)) {
                    return articles1[i];
                }
            }
            return null;
        }
    }
})

there is a separate call for each of the 13 categories to get articles.

Is there a way to set the [category_name] to a variable, possibly the state name or something to that I can just make 1 call to wordpress and the url will rely on what state the user has chosen? I have been trying to learn angular and from what I have seen I am sure there must be a more elegant way of doing something like this?

Related posts

1 comment

  1. Inject the Angular $location provider and you will have access to every part of your current URL (you can also use it to listen to the state changes). Then just build the URL to WordPress dynamically:

    .factory('Articles1', function ($http, $location) {
        // ...
    
        return {
            all: function () {
                var currentCategory = $location.path().split('/')[1]; // Assuming the category is part of the path and at the second place
                var wpUrl = 'http://www.example.com/wp-json/posts?filter[category_name]=' + currentCategory;
    
                return $http.get(wpUrl).then(function (response) { // ...
    

Comments are closed.