Exploring the concepts of AngularJS directives and resources

I've been experimenting with angularjs and rest service calls to display specific data sets, but I'm encountering challenges with custom directives and resources.

Currently, I have a custom directive that loads a list of comments in an application. This list is loaded through a resource call and displayed using the directive on Page A.

On Page B, I display information about a single user through a URL like site.com/user/3 - this user data is fetched from a REST resource and displayed successfully as the page model.

My goal is to integrate the comments directive onto the user's page so that it shows a list of comments specific to that user. I assumed I could somehow pass the user as a filter to the directive for displaying comments.

However, this approach doesn't seem to work as expected. It appears that the directive is executed before the user data promise is fulfilled, resulting in unfiltered comments being displayed.

In essence, how can I ensure that my directive loads the filtered comments only after the user data has been completely loaded?

Just to clarify, when I mention users and comments, it's for illustrative purposes. The actual data is more domain-specific, but the concept remains the same. I haven't included any code intentionally because I want to focus on understanding the correct methodology rather than troubleshooting specific code issues.

Answer №1

Personally, I'm not a big fan of strict rules, but here's how I see it:

  • When it comes to directives, they should mainly focus on DOM manipulation and presentation. It's best to keep them as self-contained, reusable components. For example, your directive should be responsible for displaying a list of comments on the UI.
  • Tasks such as interacting with the server, filtering comments, etc. are better handled by a service that your directive depends on. In your scenario, you could have a method in the service called getUserComments = function(userID) which fetches the user's comments. The directive then uses this data to update its portion of the DOM.

This is what the structure would look like:

angular.service('CommentService',
    function($http, $q){

        this.getUserComments = function(userID){

            var deferred = $q.defer();

            $http.get('site.com/user/' + userID).
                success(function(comments) {

                   deferred.resolve(comments)

                }).
                error(function(data, status) {

                   deferred.reject(status);

                });

            return deferred.promise;
        };

    }
); // End CommentService

angular.directive('commentList',
   function(CommentService){

      return {
         restrict : 'EA',
         template : '<ul><li ng-repeat="comment in comments">{{comment.text}}</li></ul>',
         scope : true,
         replace : true,
         link : function(scope, elem, attrs){

             // get User ID from somewhere
             var userID = 3;
             CommentService.getUserComments(userID).then(
                 function(comments){
                    scope.comments = comments;
                 }
             );

         }  
      }
   }
);

Hopefully, this explanation clears things up!

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

Storing user credentials in Firestore after registration - best practices

Hi, I need some assistance with storing user credentials in Firestore after they sign up. Unfortunately, I keep encountering the following error: Invalid collection reference. Collection references must have an odd number of segments, but userDatabase/QMJ ...

Optimal strategy for creating a kiosk application that features dynamically changing views based on a timer

Currently, I am developing an app with 6 different views, each paired with its own controller. I am interested in implementing an automatic view switch after a certain number of seconds, looping back to the beginning once it reaches the end. In addition, ...

Sinon.stub functions as expected in karma and mocha when using Chrome, however it encounters issues when running in head

In my current project with AngularJS, I have implemented a feature where scrolling on an element triggers the scrollTop() function to determine if another method needs to be executed. I created a sinon.stub for this purpose: scrollTopStub = sinon.stub($. ...

Is it considered poor form for an Angular controller to invoke a function on a directive?

My custom Angular directive functions as a unique combobox, where clicking on the input control reveals a div below it with a list of items from a model object. The user can type text into the input control to filter the displayed list. In addition to the ...

There are a few steps to take in order to sort an array of objects by a

I want to organize and display data in a sortable table format javascript let dataList = [ { idx: number, name: string, btn: number, index: number }, { idx: number, name: string, btn: number, index: number }, { idx: number, name: string, btn: number ...

Troubles encountered with adapting apexcharts size within a react environment

As a novice front-end coder transitioning from a data analyst background, I am currently facing an issue with integrating an ApexChart visual into a flexbox element. The visual appears fine at a resolution of 2560x1440 pixels. However, upon further resizin ...

Error: Attempting to append a child to a non-existent property

I am currently learning Java Script and this is the code I have been working on. <!doctype html> <html> <head> <style> div {position:absolute; width:500px; height:500px} img {position:absolute} ...

Issue with Bootstrap Carousel Interval Setting not Functioning as Expected

I recently added Twitter Bootstrap-Carousel to a website with the intention of using it to navigate through different sections of a module. However, I'm encountering an issue where setting the interval to false does not work as expected. When I set an ...

Modifying SASS variable values based on the presence of specific text in the page URL

How can I utilize the same SASS file for two different websites with similar functionality but different color schemes? My goal is to dynamically change the color based on the URL of the page. However, I am facing challenges in extracting the page URL from ...

One of the two identical pages is experiencing issues with the jQuery leanmodal while the other is

Despite having the same scripts and libraries loaded in two pages with identical templates, there is a slight difference in main content. Strangely, leanmodal only seems to work on the index page and not on any other page. <script type="text/javascrip ...

extract values from a JavaScript function on a website

Currently, I am facing a challenge in automatically retrieving elements from a webpage and I seem to be stuck on a few things. My approach involves looping through all classes named 'trList' using document.getElementsByClassName('trList&apo ...

Enhance JSON nesting with knockoutJS

I am currently working on updating a JSON object in memory using the knockout.js user interface. However, I have encountered an issue where changes made in the UI do not seem to reflect on the JSON data itself. To troubleshoot this problem, I have added bu ...

What is the process of obtaining User properties through a URL and utilizing them as variables in JavaScript?

I need to retrieve the city properties: 918 using req.params.userMosque from the URL '/shalat/:userMosque'. I want to assign it to the variable city for customizing my API url request. However, it seems like it's not working as expected. I h ...

Is the removal of the Vue-Router link happening when you click on the top app bar icon in Google Material

Review of the following code snippet: <!DOCTYPE html> <html> <head> <title>test</title> <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='vie ...

AngularJS allows for filtering unique values per key and retrieving only the checked items

I am working with an angular object and need to display its records with filtering and sorting functionalities. Additionally, I want to show the unique values per key within the object using checkboxes. I have successfully implemented the record display ...

The largest allowable call stack size within jQuery version 1.9.0

I have a question about poorly written code that I've been experimenting with. It's messy, but it's just for fun. I was attempting to create a "like system" where a user clicks on a button and the object ID associated with the button is sent ...

I am looking to modify the file name in the save as dialog box whenever the user performs a right-click

In my current project, I am utilizing PHP along with javascript/jQuery. I have a specific requirement where I need to alter the filename displayed in the save as dialog when a user right-clicks on an image and chooses to save it. For instance, I wish to ...

OnsenUI: driving engagement with push notifications

Can notifications be sent from the app without relying on 'Push.send()' in the back-end? My app is straightforward - it uses a timer and I need to alert the user when the time expires, even if they are not actively using the app at that particula ...

Adding several lines of HTML content from an object using jQuery's append method

Currently, this is what I have: $(document).ready(function() { $.ajax({ type:"GET" , url:'{{url("/api/getcart")}}' , dataType:"json", success: function(data){ $('#price').append(data.cartitems[1].product.pr ...

What is the most efficient way to retrieve key pair values of separate elements in an array with just one API request?

The API I am working with returns an array of elements, each containing multiple key-value pairs. An example of a similar API response can be seen here: , where an array of poems is returned. [ { "title": "...." "content": "..." "url" : "..." } ...