AngularJS - one-time execution of view generation from .NET controller

Currently, I have an MVC .NET application integrated with AngularJS. In my route provider configuration, I am utilizing the controllers of MVC to retrieve the views as shown below:

   .when('/Units', {
        templateUrl: 'Unit/Units'
    })
    .when('/UnitsDetail', {
        templateUrl: 'Unit/UnitsDetail'
    })

My UnitController in .NET consists of the following methods:

 [Authorize]
    public ActionResult Units()
    {
        return View();
    }

    [Authorize]
    public ActionResult UnitsDetail()
    {
        ViewBag.reference = Guid.NewGuid().ToString().Substring(0, 6);
        return View();
    }

In the UnitsDetail view, it is necessary for me to have a unique reference generated within the UnitsDetail() method.

An issue arises when navigating from Units to UnitsDetail multiple times. Initially, the UnitsDetail() method is invoked, generating a new reference. However, upon returning to Units and revisiting UnitsDetail, the method is not triggered again resulting in the same reference being displayed. It is imperative that a fresh reference is generated each time.

Although I could potentially generate the reference using JavaScript on the client side or make an AJAX request from Angular to the server, my main query revolves around how to prompt Angular to call the UnitsDetail() method whenever "#/UnitsDetail" is accessed.

Any insights or suggestions would be greatly appreciated!

Answer №1

By default, Angular will store all views in its template cache for faster access.

This caching behavior is intentional on Angular's part. The framework expects the view to contain mostly static HTML with dynamic elements indicated by {{ dynamicScopeVariable }}. When rendering the view, Angular will replace the dynamic parts with values from scope objects while displaying the static content directly from the cache.

Upon the first execution of a view, it will be cached for future use.

In terms of design considerations, you have two options available, with one clear choice being more favorable:

Option #1

Disable template caching in Angular by following instructions at

By disabling caching, Angular will fetch the HTML template every time it is needed, potentially impacting performance as server-side MVC actions tend to be time-consuming. While this approach may work, it underutilizes the benefits of a client-side MVC framework like Angular.

Option #2

Utilize an Angular service to retrieve a GUID from the backend using code similar to the example below:

 ViewBag.reference = Guid.NewGuid().ToString().Substring(0, 6);

If feasible, consider employing WebAPI for small requests and then updating the view with the retrieved GUID using Angular.

It's advisable to determine if generating a random unique number through JavaScript could serve your purpose instead of relying on a GUID. Depending on your specific requirements, either Option #1 or Option #2 can be implemented.

Edit: If you've attempted Option #2 already, then Option #1 becomes the recommended course of action.

Edit 2: To remove a specific element from the cache, you can utilize the following methods:

 $templateCache.remove("<Element Name>");

Alternatively, you can employ:

$cacheFactory.remove("Name")

For further details on the cache factory functionality, refer to: https://docs.angularjs.org/api/ng/service/$cacheFactory

The naming convention typically revolves around the page name, allowing you to inspect the template cache or cache factory object via debugger console for the exact identifier.

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

Using AngularJS with Highcharts

Is there a way to hide the name of series within a highchart in an angularjs environment? I'm looking for a solution to this issue. Even when I try setting it to series : [{ name:'', data:somedata }] It still shows up as "s ...

Is it recommended for synchronous code invoked by a Promise's .then method to generate a fresh Promise

I recently wrote some code containing a mix of asynchronous and synchronous functions. Here's an example: function handleAsyncData() { asyncFunction() .then(syncTask) .catch(error); } After some research, I learned that the then method is ...

Ways to update the dataTable in ReactJS post clicking the save button on the modal

Just starting my second week of diving into React. Looking for some guidance on how to update the dataTable in reactJs after clicking the save button in the modal. This is the structure I'm working with: I have a ParameterMaintenance.jsx file that ...

Add fresh HTML elements within the ng-repeat loop

I'm struggling to insert new HTML code in the middle of an ng-repeat loop. I've tried using append but it doesn't seem to work. Here is a snippet of my code: <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/aja ...

AngularJS check boxes feature for quizzes

Just starting out with angular and facing what seems like a simple issue. I have a question with multiple answers, one to three of which may be correct. Users can select their answers using checkboxes. The value field indicates whether an answer is true ( ...

`The universal functionality of body background blur is inconsistent and needs improvement.`

I've developed a modal that blurs the background when the modal window is opened. It's functioning flawlessly with one set of HTML codes, but encountering issues with another set of HTML codes (which seems odd considering the identical CSS and Ja ...

Unlocking the capabilities of Chrome extensions using Angular 2 and TypeScript

Currently attempting to develop a chrome extension using angular2 and typescript, I have hit a roadblock in trying to access the chrome API (in this case, chrome.bookmarks). I have successfully gained access to the chrome object by following guidance from ...

Is it possible to display Google pie charts when clicking on text or an image?

Having trouble setting up a link that triggers an onClick() action to generate a Google pie chart? Check out this example on JSFiddle. <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <div id="piech ...

When making a POST request with axios, the req.body object appears to be empty. However, when using the 'request' module, the body is populated as expected

Providing some context - My NodeJS server is running on port 3001 and my React application on port 3000. I've configured a proxy in my React application's package.json to redirect all requests to port 3001 - "proxy": "http://localhost:3001" H ...

How to serialize a subclass using Json.NET

When attempting to utilize Json.NET for serializing a subclass, I noticed that the resulting JSON only contains properties from the superclass and not the subclass object itself. This issue seems similar to one discussed in this Stack Overflow thread, but ...

Tips for positioning the overlay to match the icon list when hovering- JavaScript/Cascading Style Sheets (CSS)

My challenge involves a list of <li>'s accompanied by an icon that, when hovered over, displays an overlay containing information about the 'test'. The setup looks something like this: test1 test2 test3 and so forth.... Here' ...

The fulfillment of the post route for the login page is awaiting a request in the browser using Express Node.js

The router is currently waiting for a response (request pending) router.post('/loginpost',(req,res,next)=>{ var email=req.body.email; var password=req.body.password; var selectsql=`SELECT * FROM client WHERE em ...

Error encountered during navigation: navigator has not been defined

I encountered an issue where the page gets redirected upon form submission without triggering the catch block. However, in the backend, I am facing an error stating that the API body is not being executed. Below is the code snippet of the page: "use cl ...

JS editing an array in a datatable

I have created an HTML page where users can enter data, which is then uploaded to a SQL server. I have been studying DataTables to load an array into a table and tried editing it, but still haven't had success. Can anyone offer assistance? var array ...

"Exploring the capabilities of NODE JS Socket IO through request and response communication

I am currently utilizing node js and socket io in my website setup. I am encountering an issue where I need to establish a connection with the client on my website when the "client.on('Connexion', function(data) { }" is triggered. However, I am f ...

IE encounters an absolute z-index problem when expanding concealed content

I'm having trouble with the positioning of a block (div). I am new to CSS, so any help would be greatly appreciated. Here is the code snippet: http://jsfiddle.net/9rEmt/ (please check it out) for viewing online in IE. When I use absolute for positio ...

Should a Service Worker be automatically installed on each page reload, or only when a user navigates to a new page?

Currently in the process of developing a PWA. I have encountered an issue where the service worker seems to be installing on every page reload or when navigating to a different page within my app. It appears that many files are being cached during the inst ...

Tips for transforming a string into an object using AngularJS

Here is a string I'm working with: $scope.text = '"{\"firstName\":\"John\",\"age\":454 }"'; I am trying to convert it into a JavaScript object: $scope.tmp = {"firstName":"John","age":454 }; Please note: J ...

Creating a zebra-striped list using CSS can be done by styling even and odd list items differently

I am facing an issue with Angularjs and the table tag when using group loops. The problem arises in achieving correct zebra striping for the list. How can I solve this to ensure the zebra pattern is applied correctly? <table> <tbody> <tr ...

What is the best way to attach two separate event listeners to a single button?

I'm attempting to have one button trigger two different functions, but I haven't been successful so far. I tried adding the second event listener as indicated by the // part, but it didn't work. The two functions should be executed sequentia ...