What is the best way to defer the instantiation of a particular controller (not a route) in your

What I'm looking for is a directive that functions like a typical ng-controller, but I need it to be invoked only after a promise has been resolved. To achieve this in HTML, it could be implemented as such:

<div ng-controller="myCtrl" ctrl-promise="p">

Where "p" represents any promise within the parent scope. I am aware of the method to delay the instantiation of a controller for a specific route (as discussed in this answer: Angular.js delaying controller initialization), however, I would prefer to set this on a per-controller basis rather than per route. While I could use ng-if with "p" as an attribute, I am curious if there is another approach?

Answer №1

If you wish for the content inside the div to exist without being controlled by the controller until the promise is resolved, here is a solution:

Check out this customized directive that generates a controller upon promise resolution:

angular.module('myApp')
.directive('delayController', function($controller, $q) {
  return {
    scope: true,
    link: function(scope, elm, attr) {
      $q.when(scope.$parent.$eval(attr.delayControllerPromise)).then(function() {
        var ctrl = $controller(attr.delayController, {
          $scope: scope
        });
        elm.children().data('$ngControllerController', ctrl);
      });
    }
  };
});

Here's how you can implement it:

<div delay-controller="MyCtrl" delay-controller-promise="myPromiseExpr()">
</div>

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

What is the Proper Way to Add Inline Comments in JSX Code?

Currently, I am in the process of learning React and I have been experimenting with adding inline comments within JSX. However, when I try to use the regular JavaScript // comments, it leads to a syntax error. Let me share a snippet of my code below: const ...

Setting the cache to false during an httpget request in an mvc4 controller action: tips and tricks

My httpget request to a controller action looks like this: $.get('/Course/ExplanationCorrect/', postData, function (data) { $('#SurveyDiv').html(data); }); While it works on all other browsers, I'm facing an issue with IE10 o ...

Using a Typescript variable prior to its assignment

I encountered an issue in my Typescript / ReactJS project displaying the error message Variable 'myVar' is used before being assigned. TS2454 This problem arises with my TS version 4.2.3, appearing both in my IDE and during code execution. Inte ...

Mastering the ins and outs of ngStorage in AngularJS

Imagine a web page featuring a form that allows users to input multiple entries before submitting. As each entry is added, a summary of the data entered is displayed in a table at the top. Once all entries are completed, the user can then proceed to submit ...

What is the best way to determine the height of a DIV element set to "auto"?

When setting a fixed height on a div using jQuery, such as $('div').height(200);, the value of $('div').height() will always be 200. This remains true even if the content within the div exceeds that height and overflow is hidden. Is th ...

Utilize styled-components in next.js to import and resize .svg files seamlessly

I have been attempting to import .svg files into my next.js project, but I have not had any success. I tried importing the .svg files the same way as in my React project by creating a typing.d.ts file and importing the svg as a component. However, it did ...

Retrieve information from a JSON file within a Vue.js application rather than entering data manually

I am venturing into the world of Vue.js for the first time. I have created an app that currently relies on manually added data within the script. Now, I am looking to enhance it by fetching data from a JSON file, but I'm unsure about how to proceed wi ...

Express: How to Define Route Parameters from the Client Side

app.get('login/:id', function (request, response) { … }); I am curious about how the :id parameter is assigned from the user in a request like this. Since each user will have a unique id on my site, I wonder how it works. Does the user need ...

Looking to tweak the date format in a Vue.js template?

I received the following format: 2019-01-08T11:11:00.000Z However, I need it to be in this format: 2019-01-08 Does anyone know how to achieve this date formatting without using the moment package? ...

Sending images as a base64 string from a Titanium app to a Ruby on Rails web service

I am encountering an issue when trying to upload an image from an app that has been converted into a base64 string to a Ruby on Rails server. The app is developed using Titanium. However, after retrieving and decoding the image string back into an image, ...

Navigate through a series of div elements using Jquery

I need help figuring out how to make the window scroll between different divs in a sequence. The issue is that my current code only works for one specific div at a time. $('.down_arrow').click(function(e){ $('html, body') ...

Angular 2 has its own version of $q.when called RxJs

Back in the AngularJS 1.* days, I used to have this code snippet to refresh the auth-token: ... if (!refreshTokenInProgress) { refreshTokenInProgress = AuthService.refreshToken(); } $q.when(refreshTokenInProgress, function () { refreshTokenInProgre ...

Enhancing the camera functionality of the HTML <input> tag for iPhone and Android devices

I am currently working on a mobile web application that requires access to the device's camera. I am aware that this can be achieved using the following code: <input type="file" accept="image/*" capture="camera" /> The code snippet above suc ...

What is the best way to access a post request value from one JavaScript file to another in a Node.js environment

Hey there, longtime listener, first-time caller. I'm diving into the world of node JS, Javascript, and express but I've hit a roadblock that's been giving me a headache for three days now. Hoping someone here can lend a hand. I have a &apos ...

Utilizing Data Filters to Embed HTML in Vue.js?

I have been attempting to utilize the Filter feature in Vue.js to insert HTML tags within a String. The documentation indicates that this should be achievable, however, I am not having any success. The objective is for the data to be just a String that is ...

Implementing a persistent header on a WordPress site with Beaver Builder

My website URL is: . I have chosen to use beaver builder for building and designing my website. I am in need of a fixed header that can display over the top of the header image. Here is the code snippet that I currently have: <div id="header">html ...

Utilizing MongoDB's object within the mapper function in MapReduce

I have a question about querying data in MongoDB using the aggregate framework. Originally, my data was structured like this: [ { created_at: "2014-03-31T22:30:48.000Z", id: 450762158586880000, _id: "5339ec9808eb125965f2eae1" } ] Now, ...

Invalid element type detected. A string was expected, but instead found undefined

Following a recent update of next-auth, an unexpected error has surfaced: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your compon ...

AngularJS not swapping the data-url with the scope URL provided in {{ uploadUrl }}

Currently, I am utilizing jQuery fileupload to send a file to a specific URL. Within my controller, the code snippet below demonstrates how I generate the URL for uploading: uploadService.getUploadURL($scope.projectId).then(function (url) { $scope.up ...

Display data as a JSON object using Highcharts

Looking to populate a highchart in Jade using JSON data sent from Node.js. Currently, I have successfully added static data as shown in the code snippet below: var series = [ { name: 'Tokyo', data: [7.0] } ]; Now, I am attempti ...