Angular directive loads after receiving variables

In my project, there is an Angular directive responsible for loading data from a service. However, the data is being loaded using a variable obtained from a controller, which in turn was loaded from a service.

Below is the code snippet for the directive:

app.directive("posts", ['Posts', function(Posts) {
return {
    restrict: 'E',

    template: '' +
    '<div ng-repeat="post in posts"></div>',
    scope: {
        showLoading: '&',
        hideLoading: '&',
        spot: '@'
    },

    controller: ['$scope', function ($scope) {

    }],

    link: function(scope, element, attrs) {
         $scope.load = function () {
            Posts.loadPostsBySpot(scope.spot)
        };
    }
};
}]);

Next, we have the controller code:

app.controller('spotPageController', ['$scope', 'Spots', function ($scope, $Spots) {

    doit = function () {
        Spots.getSpot($)
            .success(function (data) {
                $scope.spotId = data.data;
                console.log($scope.spot);
            }).error(function (data) {
                console.log('error');
            });
    };
 }]);

Inside the HTML file:

<posts spot="{{spotId}}" showLoading="showLoading()" hideLoading="hideLoading()"></posts>

One issue faced is that when the directive is loaded, the "spot" variable is not yet set. How can we ensure that the directive loads only after the spot is set?

Answer №1

To achieve this, utilize the ng-if directive.

<posts ng-if="spotId" spot="{{spotId}}" showLoading="showLoading()" hideLoading="hideLoading()"></posts>

The element will only appear after the initialization of spotId. This prevents the directive from being triggered before that point.

If you prefer to package this functionality into a directive, you can monitor changes in the scopeId. Visit the fiddle for an example.

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

The elastic image slideshow maintains the original size of the images and does not resize them

When utilizing the elastic image slider, I encounter a similar issue as described at Elastic Image Slideshow Not Resizing Properly. In the downloaded example, resizing the window works correctly. However, when trying to integrate the plugin with Twitter B ...

Incorporate an HTML form into the primary HTML webpage using AngularJS application technique

As a newcomer to AngularJS, I am attempting to grasp how it can be integrated with an ASP.NET-MVC5 application. For my initial test, I want to launch an AngularJS app from a basic HTML page (in this case index.html) where the app contains a form template i ...

Displaying NodeJS error messages directly in the main HTML file

After creating a form using NodeJs and implementing input validations that display errors when users enter incorrect values, I encountered an issue where the errors appear on a new blank page instead of within the main HTML file itself with stylish formatt ...

Organize every rectangle and text element in D3 into distinct groups

Currently, I am working on creating a bar graph using d3.js. The goal is to display text on top of each bar when the user hovers over it. To achieve this, the <text> and <rect> elements need to be grouped inside a <g> element. For Exampl ...

Experiencing a problem with the JavaScript loading function

An error was logged in the console SyntaxError: unterminated string literal A piece of code is supposed to display a notification $(document).ready(function () { alertify.success("Success log message"); return false; }); Despite testing the cod ...

What is the best way to implement jQuery after new elements have been added to the DOM?

I'm currently working on a Sentence Generator project. The program is designed to take a list of words and retrieve sentences from sentence.yourdictionary.com based on those words. The first sentence fetched from the website is displayed using the cod ...

Is there a way to dynamically set the value of a React Material TextField in Auto Select mode?

Here is a React state: const [filterByInvoiceNo, setFilterByInvoiceNo] = useState( 0 ); This represents a React Material TextField: <TextField size="small" type="number" label="Invoice No&quo ...

Unauthorized changes made without verification

I'm in the process of developing a website that allows users to post without needing to create an account. Upon posting, users will be prompted to enter their email address. After posting, users will receive an email with a unique URL that grants th ...

Issue with NodeJS proxy not functioning correctly

The current request route starts at localhost:3001, passes through a proxy located on the same localhost at localhost:3001/proxy, where it is then directed to the Salesforce instance. The ExpressJS proxy and AngularJS client-side app are utilized for this ...

Place the item at the top of the list before scrolling downwards

I'm struggling with what seems like it should be a simple task. My goal is to add new items to the top of a list and have the list scroll down to show the new item. So far, I've managed to create and add a new list item using this code snippet: ...

What is the method for initializing fancybox with the precise image index?

My current usage of fancybox involves the following code snippet: $("a[rel=Fancy" + UserId + "].Items").fancybox({ 'autoscale': 'false', 'cyclic': true, 'transitionIn': 'elastic', & ...

Concatenate a variable string with the JSON object key

I am currently working on a request with a JSON Object structure similar to the following: let formData = { name: classifierName, fire_positive_examples: { value: decodedPositiveExample, options: { filename: 'posit ...

Utilizing jQuery and Isotope for intricate filtering

My isotope instance contains elements with multiple parameters, as shown below: <element data-a="1 2 3 4 5" data-b="1 2 3 4 5" data-c="1 2 3 4 5" Filtering for an element that has A1, B2, and C3 is straightforward: .isotope({ filter: '[data-a~=1 ...

Create a bespoke AngularJS directive for a customized Twitter Bootstrap modal

I am attempting to create a unique custom Twitter Bootstrap modal popup by utilizing AngularJS directives. However, I'm encountering an issue in determining how to control the popup from any controller. <!-- Uniquely modified Modal content --> ...

Combining multiple JSON objects into a single array in AngularJS

Currently, I am facing a challenge in merging two API calls. The first call involves fetching data by filtering the account_id on the backend, while the second call retrieves data based on the test_id. Let's start with the JSON response for /api/test ...

What is the process for importing a file with an .mts extension in a CJS-first project?

Here's a snippet from a fetchin.mts file: import type { RequestInfo, RequestInit, Response } from "node-fetch"; const importDynamic = new Function("modulePath", "return import(modulePath);") export async function fetch(u ...

Preventing redirection post-AJAX call using jQuery

Currently, I am attempting to implement a basic form submission using AJAX to send data to submit.php for database storage. However, upon submission, the page redirects to submit.php instead of staying on the current page. How can I make it submit without ...

What is the best way to assign multiple values to certain elements within an array?

I have an array that looks like this: items = { item1: 10, item2: 5, item3: 7, item4: 3, }; I am looking to include additional details in this array, for example: items = { item1: 10 {available: true}, ...

I am encountering a problem with the image source in my Next.js project

I've encountered an issue with using Sanity image URLs in my project. The error message displayed in my console page reads: next-dev.js?3515:25 Warning: Prop src did not match. Server:"https://cdn.sanity.io/images/jbcyg7kh/production/4f6d8f5ae1b ...

Leveraging fetch for sending JSON payloads

I am currently facing an issue while attempting to post multiple points of data from a form input. Despite my efforts, it seems that the form data does not make it to the json output payload as expected. I have verified this through network output inspect ...