Learn how to dynamically load a new controller in AngularJS without affecting the current URL

There is a URL structure like /products/:product_id

In the controller, I validate the existence of the product ID, and if it doesn't exist, I want to load a controller that will display a message saying "Product not found".

I am searching for a function similar to:

$location.path('/product_not_found');

but without altering the URL displayed in the address bar.

Any suggestions?

Thank you!

Answer №1

When using angularjs, it becomes easy to add attributes to HTML tags. For instance, when displaying a product if it is found or showing a message if not, I find the ng-show attribute particularly useful. Here's an example:

Using ng-show ensures that you do not affect the URL because the content is already loaded.

HTML:

<html ng-app="productDisplay">
<head>
    <title>Product info</title>
    <script src="js/angular.js"></script>
    <script src="js/app.js"></script>
</head>
<body>
    <div id="content" ng-controller="ProductController as productCtrl">
        <div ng-show="status === 'waiting'">
            <p>waiting for product to load..</p>
        </div>
        <div ng-show="status === 'found'">
            <!-- display product info here -->
            <p>Name: {{ product.name }}</p>
            <p>Price: {{ product.price }}</p>
        </div>
        <div ng-show="status === 'not-found'">
            <p style="color: red;">Not found such product</p>   
        </div>
    </div>
</body>
</html>

JS:

(function() {
    // Can only access variable app within this function scope
    var app = angular.module('productDisplay', []);

    app.controller('ProductController', ['$scope', function($scope) {
        $scope.product = {name: '', price: ''};
        $scope.status = 'waiting';

        this.getProduct = function() {
            found = false;

            /** Some code checking if product found */

            if (!found) {
                $scope.status = 'not-found';
                return {};
            } else {
                $scope.status = 'found';
                return {name: 'BBB', price: '123$'};
            }
        };

        $scope.product = this.getProduct();
    }]);
})();

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 best method for choosing an Edit button that does not have any text within an ng-repeat component?

Within my Form builder, I am able to select a field type using ng-repeat and it automatically appears in the canvas. My goal is to click the Edit button of that specific element on the canvas. Whenever the edit button is clicked, additional fields are disp ...

Is there a way to dynamically integrate the Insert Column feature into the ContextMenu of a Syncfusion Treegrid?

What is the best way to add Insert Column functionality to the ContextMenu of a Syncfusion Treegrid? Insert Column Rename Column Delete Column ...

Error: The Angular-Summernote editor is unable to upload images, as the object

I'm having difficulty understanding how to utilize the angular-summernote callback on-image-upload. Here's the code in my view: <summernote data-editable="editable" data-on-image-upload="imageUpload(files, editor)"></summernote> My ...

JS: Submitting form data through POST method but fetching it with GET method?

When using PHP to retrieve data, the $_POST method cannot be used; only $_GET. Why is that? Could it be that I am not sending my form data correctly? I assumed that by using request.open("POST"), the form would be processed as a POST request rather than a ...

When the browser's inner width is less than the inner height, use jQuery or JavaScript to show a message on the webpage

I've been having trouble getting this to work and I've attempted various solutions suggested by different sources such as: Display live width and height values on changing window resize php echo statement if screen is a certain size And more, b ...

Best Practices for Implementing Redux Prop Types in Typescript React Components to Eliminate TypeScript Warnings

Suppose you have a React component: interface Chat { someId: string; } export const Chat = (props: Chat) => {} and someId is defined in your mapStateToProps: function mapStateToProps(state: State) { return { someId: state.someId || '' ...

Load image asynchronously using a mirror server in React/Next.js with a set timeout time

For my website, I have decided to store all of my images on IPFS, which are pinned successfully. This has helped reduce traffic and keep costs within the free tier offered by my hosting provider. However, at times the IPFS url may not load fast enough dep ...

Put <options> into <select> upon clicking on <select>

Is there a way to automatically populate a <select> list upon clicking on it? $(document).ready(function(){ $("body").on("click", "select", function(){ ajax(); //function to add more <option> elements to the select }); }); Loo ...

Converting a jQuery function into AngularJS: A step-by-step guide

I'm completely new to AngularJs and I recently created a slider function using jQuery. Now, my goal is to convert this function into Angular. Below is the code snippet that I have: <div class="slide-container"> <div class="slide-s ...

JQuery post request not providing the expected response after posting

I have a post request var prodId = getParameterByName('param'); var pass = $('#password1').val(); $.post("rest/forget/confirm", { "param" : prodId, "password" : pass }, function(data) { ...

When attempting to incorporate a video using Sencha, an error occurs stating that the resource is being interpreted as an image but is being

While attempting to incorporate a sample into Sencha, I encountered an error stating "Resource interpreted as Image but transferred with MIME type text/css". Ext.define('MyApp.view.Newpage', { extend: 'Ext.Video', xtype: ' ...

error encountered in ajax contact form due to issue with select element

I'm experiencing an issue with my ajax contact form, where the input field and select element are not providing the expected results. This is the HTML Form Code (with "name" as the input and "iphone" as the select element) <div id="contact_form" ...

Preventing html entities in emails sent using Laravel and Summernote: A guide

I'm encountering a problem with Laravel 5.1 and summernote. I am utilizing summernote to compose an email, which is then sent via angular.js to a laravel 5.1 API. Despite my efforts to troubleshoot, I can't seem to send the email in HTML format ...

My local requests are being blocked by both Chrome and Firefox

Recently, I've been experimenting with local flash development and trying to inject my swf file into a website served by my test server. To enable loading of local resources in Chrome, I set --disable-web-security. In FireFox, I made the following a ...

Is it possible to search a JSON Array using a variable as the criteria

I have a JSON Array that needs to be searched: [ { "Device_ID":"1", "Image":"HTC-One-X.png", "Manufacturer":"HTC", "Model":"One X", "Region":"GSM", "Type":"Phone" }, { "Device_ID":"2", "Image":"Motorol ...

What is the reason for me continuously receiving the error "cannot read map of undefined"?

Having trouble debugging my redux sagas and react integration. No matter what initial state I set, I keep running into undefined errors when trying to map through the data. I've tried null, undefined, and empty arrays but nothing seems to work. Can a ...

Creating a JSON file that contains a collection of discord.js statuses and then seamlessly integrating it into the primary JavaScript document

const userActivities = [ { name: "Morning Jog", type: ActivityType.Running }, { name: "Afternoon Nap", type: ActivityType.Sleeping }, { name: "Evening Game Night", type: ActivityType.Gaming }, { name: "Late Night Code ...

What are the steps to activate the hot-swapping feature for HTML and JavaScript files in IntelliJ's Community edition?

Just starting out with IntelliJ to work on an AngularJS project with spring-boot as the backend server. Every time I make changes to my HTML or JavaScript code, I find myself needing to restart the app server. Is there a configuration setting or plugin ava ...

Initializing the $(this) variable prior to the function declaration

I am faced with the task of performing multiple checks based on the IDs of certain elements, all of which vary slightly. So, I created several functions to handle this, and rather than repeatedly using $(this).children ..., I wanted to create a short vari ...

Ways to retrieve information from a different website's URL?

Having a bit of an issue here. I'm currently browsing through some reports on webpage #1 () and I have a specific requirement to extract the object named "data" from webpage #2 (). However, the code I've used seems to fetch the entire webpage ins ...