Why isn't the array data displaying on the HTML page in AngularJS even though the ng-click function is being called?

My ng-click function is working properly on a tab and I am receiving the list from the service correctly. However, the data is not reflecting on the HTML page. I am unable to figure out what the issue is with my code. Please review my code and let me know where I may have gone wrong.

/**
 * @Summary: Function to getUserCategory, retrieves the User selected Category.
 * @param:   callback
 * @return:  callback(response).
 * @Description: 
 */
//Defining function for getUserProfile in service 
$scope.getUserCategory = function () {
    var data = {
        userTypeKeyId: Number(AUTH.userTypeKeyId),
        fieldKeyId: Number(AUTH.defaultFieldKeyId)
    };
    IntermediaryDashboardService.getIntCategory(function (response) {
        if (response != null) {
            if (response.data.isSuccess) {
                $scope.userCategories = response.data.userCategories;
            }
        }
    }, data);
};


/**
* @Summary: Function to getIntCategory, retrieves the IntCategory
* @param:   callback, data
* @return: 
* @Description:
*/
this.getIntCategory = function (callback, data) {
var url = '/api/userCategories/filter/list/each';
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data
}).then(
function (response) {
//Success Function
callback(response);
},
function (response) {
//Failure function
callback(null);
}
}
<ul ng-repeat="category in userCategories" class="ng-cloak">
<li style="padding-top: 11px;">
<a href="#" ng-click="getAlbumInIntermediary(category.categoryKeyId)">
{{category.categoriesDto.categoryName}}
</a>
</li>
</ul>

Answer №1

Easy to use

ng-if="intermediateAlbum.length"

0 is considered false in this case.

Answer №2

However, the information is not showing up on the webpage.

Avoid mixing callbacks with Promises.

When making an asynchronous call and resolving the original Promise within a Service, it's better to create a new Promise and resolve it in your controller like this:

 this.getIntCategory = function (callback, data) {

   var deferred = $q.defer(); 
   var url = '/api/userCategories/filter/list/each';
   $http({
      method: 'POST',
      url: url,
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
      return str.join("&");
      },
      data
    }).then(function (response) {
       deferred.resolve(response.data);
      },
      function (response) {
        deferred.resolve({});
    });
     return deferred.promise;
   }

You can then use it in the controller as follows:

 $scope.getUserCategory = function () {           
    IntermediaryDashboardService.getIntCategory().then(function (result) {
          $scope.userCategories = response.data.userCategories;                           
    }, function (result) {
        alert("Error: No data returned");
     });    
  }  

Fiddle

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

Displaying and Concealing Table Rows using Javascript

I am working with an array of prices that are being displayed in a table using a foreach loop. The goal is to hide specific rows in the table based on certain conditions. The $status variable is set to "YES" if the price is => 30, and "NO" if the price ...

Verify that all keys of an object are present as values in an array of objects

Imagine having two entities like the following: const obj1 = {key1: "", key2: "", key3: ""}; const array2 = [ { name: "key1", }] Is there a way to verify if array2 contains an object with the same name as ea ...

Tables that respond to changes in screen size, allowing nested table cells to inherit widths

I am currently working on a responsive table with unique content in each row and a concertina feature for expanding rows. When the concertina is activated, it adds another row to the table below the current row, using a td element with a colspan attribute ...

Display a popup on a button click or icon click in ASP.NET

On Facebook, you may notice that you have 4 friend requests or notifications in the small mail icon on the right side. When you click on it, a pop-up appears with an accept button, and once you accept, it disappears and the remaining three requests are sho ...

Steps for eliminating empty values from the JSON data

How can I eliminate the properties that have null values in the following input data? var data = [ { "Id": "parent", "Function": "Project Management", "Phase": "(Null)" }, { "Id": "1", "Function": "R&D Team", "Phase": "parent" }, ...

I am unable to retrieve data using JavaScript

I am struggling to fetch data with JavaScript and display it in the console. Can anyone point out what I might be doing incorrectly? main.js // ADD TO CART $("#addToCartBtn").on('click',function(){ var _qty=$("#productQty") ...

Unable to prepend '1' to the list

My goal is to display a list as '1 2 3...', but instead it is showing '0 1 2...' var totalLessons = $('.lesson-nav .mod.unit.less li').length; for (var i = 0; i < totalLessons; i++) { $('.lesson-nav .mod.unit.les ...

The spaces between HTML elements within the pre tag are known as line gaps

I attempted to include some html tags within a pre tag, but noticed a significant gap between lines. Below is the HTML code I used: <h5>Help Message</h5> <pre ng-show="panel.info_mode == 'markdown'" ng-bind-html="panel.help_m ...

Tips on optimizing website performance by implementing lazy loading for images and ensuring they are ready for printing

Many websites feature an abundance of images, prompting the use of lazy loading to enhance load times and reduce data consumption. But what happens when printing functionality is also required for such a website? One approach could involve detecting the p ...

Creating a clickable link for every identifier

I am trying to create a sidebar navigation for my HTML page that contains multiple elements with unique id attributes. Is there a way to generate bookmark links for each id in a separate location instead of placing them next to the elements? Alternatively ...

Setting the default profile in Google Chrome using Protractor is a simple process that can be

Is there a way to run tests using the default Google Chrome profile where cache and cookies are enabled during the test runs? I've attempted the following options without success: capabilities: { 'browserName': 'chrome', &ap ...

Present intricate JSON data using only one ng-repeat in AngularJS

I am currently attempting to showcase all the books within a specific series. Initially, I utilized nested ng-repeat and achieved the desired outcome. However, with recent modifications to the layout requirements, I am no longer able to use nested ng-repea ...

Creating a popup trigger in ReactJS to activate when the browser tab is closed

I am currently working on an enrollment form that requires customer information. If a user fills out half of the form and then attempts to close the tab, I want to trigger a popup giving them the option to save and exit or simply exit. While I have a jQue ...

Is there a way to retrieve the original value of the substr value?

I successfully retrieved the correct value using the substr() method, but I am facing difficulty in getting back the original value. Can someone please guide me on how to achieve this? For example: "AAAAAA" -> AA... but I am unable to revert from AA.. ...

Issue with Ajax reload functions malfunctioning

Embarking on a new journey, I am diving headfirst into the world of web development. As an artist and writer, I have recently delved into the realm of creating a project that integrates a cms, project manager, and database front-end using php, mysql, and j ...

What is the syntax for implementing a for loop/for each loop in EJS?

I'm trying to figure out how to include this code snippet inside <% %>. I'm not sure if it's similar to a typical forEach/for loop. The documentation on EJS site is quite limited, so I've turned to this forum for help. <% incl ...

React component unmount function not being triggered when anchor tag is clicked

When a component is unmounting, I want to save the URL in local storage: componentWillUnmount(){ console.log("componentWillUnmount will be called here."); console.log("window.redirect.url", window.location.pathname); localStorage. ...

What is the best way to modify this state without altering the original array?

I am seeking guidance on how to avoid mutating state in a specific scenario: In my React Hooks setup, I have a TodoList component that displays a list of TodoItems. Each TodoItem can be clicked to trigger a function called toggle, which switches its compl ...

"Utilizing the powerful combination of Spring Boot, Spring Security,

I am new to the world of spring and I want to develop a spring boot - angularjs application that includes CRUD operations. The clients are requesting LDAP and local JDBC authentication methods as well as a common authorization mechanism for all users. Use ...

Using VueJS to apply a single component to multiple routes in a neat package

I have created three routes in my web app: /login, /signup, and /forgot, each with their own components containing basic forms. I want to include these components within a landing page component without integrating the landing page logic directly into the ...