Implementing a custom method for $resource in a controller

Running my factory:

serviceCall:

'use strict';
app.factory('serviceCall', ['$resource', 'ngAuthSettings', function ($resource, ngAuthSettings) {
  var serviceBase = ngAuthSettings.apiServiceBaseUri;

  return $resource(serviceBase + 'api/category/', {}, {
    update: {
      method: 'PUT'
    },
    getAllByCategory: {
      url: serviceBase + 'api/category/GetAllByCategory',
        method: 'GET', isArray: true
    }
  });
}]);

Now onto my controller:

displayController:

'use strict';
app.controller('displayController',
    ['ngAuthSettings', '$scope', 'serviceCall', '$routeParams', '$location',
    function (ngAuthSettings, $scope, serviceCall, $routeParams, $location) {

    function initialize() {
        var searchQuery = $location.search();
        var keywords = searchQuery.keywords;            

        var informationModel = serviceCall.getAllByCategory({ categoryId: 2, page: $routeParams.page });

        $scope.categoryInformation = informationModel.ads;
        $scope.totalItemCount = informationModel.totalCount;
        $scope.pagingSize = ngAuthSettings.maxPagingSize;
    }
    initialize();
}]);

Curious as to why informationModel.ads is consistently undefined. Is there a better approach to calling $resource custom methods in controllers?

Answer №1

Due to the prompt response time required, it is recommended to include assignments within a promise/action after accessing resources.

'use strict';
    app.controller('searchController', ['ngAuthSettings', '$scope', 'myService', '$routeParams', '$location',
        function (ngAuthSettings, $scope, myService, $routeParams, $location) {
            function initializeSearch() {
                var searchParams = $location.search();
                var searchKeywords = searchParams.keywords;            
                var dataModel = myService.getAllByCategory({ categoryId: 2, page: $routeParams.page }, 
                    function() {
                        $scope.categoryAds = dataModel.ads;
                        $scope.bigTotalItems = dataModel.totalCount;
                        $scope.maxSize = ngAuthSettings.maxPagingSize;
                    }
                );

            }
            initializeSearch();
        }
    ]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Unable to access the 'stateUpdate' property (a function) because it is undefined when passing data from a parent component to a child component

I seem to be encountering a problem with passing a function from the parent to child component in react js. Even after attempting to pass the value to the component as props, I keep getting a type error mentioned in the question. It's puzzling why th ...

Utilizing jQuery and JSON to showcase the contents of an array

My goal is to display all the items in an array by utilizing JSON and jQuery from the Song of Ice and Fire API. Currently, I am only able to display one item from each of the arrays. If you want to view the codepen, click here: https://codepen.io/frederic ...

What is the reason for the directional light shining on the box from behind?

I have inserted a DirectionalLightHelper into my code to provide lighting for a box. The light source is positioned at coordinates (2,2,1), and there are two boxes located at (0,0,0) and (3,3,3) respectively. Surprisingly, the box at (3,3,3) is also being ...

Having trouble with my ajax success function, could use some assistance please

Having issues passing values from an AJAX request to a PHP file. The error function seems to be working, but I can't figure out what's wrong with my code. Here is what I have: <script> function test(){ //alert("hello"); var myD ...

Having some issues with ng-hide in angular, it doesn't seem to be functioning properly

<nav class="menu-nav"> <ul> <li class="menu-li" ng-model="myVar"><a>Discover<i class="fa fa-chevron-down pull-right"></i></a> <div class="sub-menu" ng-hide="myVar"&g ...

Dynamically adding a new Bootstrap switch using only Javascript: a step-by-step guide

How can I dynamically add a new Bootstrap switch using only JavaScript? Here is an example: <div class="toggle btn btn-primary" data-toggle="toggle" role="button" style="width: 61.0781px; height: 38px;"> < ...

Having trouble getting jQuery css() function to work properly?

<a href="https://www.timeatthebar.co.uk" target="_blank"><img id="icon-img" src="assets/img/tabicon2.png" class="position-absolute top-50 start-50 translate-middle" style="max-width:113px; top ...

No longer will popups be blocked

I've been trying to work with jQuery to create a popup. But I'm facing an issue where my code is being blocked by Google. Here is the code snippet: <script type="text/javascript"> $(document).ready(function () { var flag = true; ...

Steps for incorporating a toggle feature for displaying all or hiding all products on the list

Looking for some guidance: I have a task where I need to display a limited number of products from an array on the page initially. The remaining items should only be visible when the user clicks the "Show All" button. Upon clicking, all items should be rev ...

Disrupting methods on a dependency within QUnit can cause tests against that dependency to fail

Currently, in my Google Apps Script project, I am unit-testing an application using QUnit for test-driven development purposes. Code Under Test The function I am currently focusing on testing and developing is the creation of a Sheet from a long string o ...

Unexpected Behavior in Angular ES6 Controller As Pattern

Forgive the uninspired title, as I am struggling to articulate my query. I have two nearly identical classes that are exhibiting slight variations in behavior. Additionally, there is a perplexing discrepancy where one class triggers a "this method can be s ...

Learn the technique to easily close multiple dynamically added fields in one go using jQuery

Check out my fiddle at the following link: http://jsfiddle.net/ZUDLH/8/ Here is the code snippet: <table id="table"></table> <input type="button" id="addRowBtn" style="border-style: none; cursor: pointer; ...

Access an object's property from within a callback function

I have an async.series() function that is calling a method from another Javascript object: main.js var obj1 = require('./obj1'); var obj2 = require('./obj2'); async.series([ obj1.myFunc1, obj2.anotherFunc ]); obj1.js module ...

Having trouble retrieving JSON data from backend server in Svelte framework

My goal is to retrieve JSON data from the Backend, specifically information about music videos. It should be a simple task, but I am encountering some difficulties. I attempted to follow a tutorial provided at: . The tutorial demonstrated fetching data wi ...

Angular 2 - Karma is having trouble locating the external template or style file

The file structure for this project (taken from the Angular 2 official site) is as follows: https://i.stack.imgur.com/A6u58.png Upon starting Karma, I encountered errors indicating that two files were not found under /@angular/... To resolve this issue, ...

The content section sits discreetly behind the sidebar

Upon loading my Bootstrap 5 webpage, the toggle button successfully moves the navbar and body section to show or hide the full sidebar. However, an issue arises where the body section goes behind the sidebar when using the toggle button. Below is a portio ...

Modify the Style of a div Element by Clicking in AngularJS

Just starting out with angularjs and trying to figure things out. Here is how I have been selecting a div: var myEl = angular.element(document.querySelector('#test')); I want to know how to add a click event to "myEl" in the controller instead ...

Techniques for displaying images in JavaScript through iteration

I am currently working on a function where I need to display photos using a loop. In the 'name1' variable, I have the file location of the photos and it changes with each loop iteration. When I use console.log, I can see the file path like "cardI ...

Problem with XRController Raycast Range

Having trouble with raycasting in THREEJS using the XR controller when trying to detect objects beyond a distance of 40 units. Raycasting works perfectly within 40 units. Referenced the example in THREEJS: Any suggestions on how to extend the raycasting ...

The function chrome.notifications.create() is producing incorrect notification IDs upon clicking

Greetings for my first post here. I've been struggling with an issue in a personal project lately. I remember coming across a similar topic on this forum before, but now I can't seem to find it. As far as I recall, the question went unanswered. ...