Challenges with directing angular directives

Setting up my first angular project and struggling with routing.

Initially see the template set by preferencesDirective on page load, works well.

Clicking "Change Template" button doesn't switch to another template. Even though debugger shows 404 error for invalid urls in $routeProvider, nothing happens when url is valid. How can I make it change correctly?

Thanks.

<div id="PreferencesApp" class="" ng-app="clientPreferencesModule">    
    <preferences-directive factory-settings="clientPreferences"></preferences-directive>
    <a href="#Details">Change Template</a>
</div>


<script>

app = angular.module("clientPreferencesModule", ["ngResource", "ngRoute"]);

app.config(function ($routeProvider) {        
    $routeProvider.when("/", { controller: "clientPreferencesController", templateUrl: '/AngularTemplates/ClientPreferences/PreferencesTemplate.html' });
    $routeProvider.when("/Preferences/:id", { controller: "clientPreferencesController", templateUrl: '/AngularTemplates/ClientPreferences/PreferencesTemplate.html' });
    $routeProvider.when("/Preferences", { controller: "clientPreferencesController", templateUrl: '/AngularTemplates/ClientPreferences/PreferencesTemplate.html' });
    $routeProvider.when("/Details", { controller: "clientPreferencesController", templateUrl: '/AngularTemplates/ClientPreferences/DetailsTemplate.html' });                
});

app.controller('clientPreferencesController', clientPreferencesController);

clientPreferencesController.$inject = ["$scope", "$resource", "$rootScope", "$http", "$route", "$location"];

function clientPreferencesController($scope, $resource, $rootScope, $http, $route, $location) {        
    this.model = @Html.Raw(JsonConvert.SerializeObject(Model));        
    $scope.location = $location.path();        
}

app.directive('preferencesDirective', preferencesDirective);

function preferencesDirective() {

    return {
        restrict: 'EA',
        scope:
        {
            factorySettings: '='
        },
        controller: 'clientPreferencesController',
        controllerAs: 'pc',
        bindToController: true,
        templateUrl: '/AngularTemplates/ClientPreferences/PreferencesTemplate.html'
    }
}

</script>

Answer №1

In order for routing to function properly, it is necessary to develop various views along with their corresponding controllers and include directives within those views. Additionally, the ng-view directive needs to be present in index.html where all the route views will be loaded. The preferencesDirective should specifically contain reusable unique functionality and the complete app view to allow for different views with varying data sets and components.

<div id="PreferencesApp" class="" ng-app="clientPreferencesModule">    
    <a href="#Details">Change Template</a>
    <div ng-view></div>
</div>

For handling different routes, each can have its own controller or a single controller if desired, separate from the directive's controller. This configuration may look like:

app.config(function ($routeProvider) {        
    $routeProvider.when("/", { controller: "viewController", templateUrl: '/AngularTemplates/ClientPreferences/PreferencesTemplate.html' });
    $routeProvider.when("/Preferences/:id", { controller: "viewController", templateUrl: '/AngularTemplates/ClientPreferences/PreferencesTemplate.html' });
    $routeProvider.when("/Preferences", { controller: "viewController", templateUrl: '/AngularTemplates/ClientPreferences/PreferencesTemplate.html' });
    $routeProvider.when("/Details", { controller: "viewController", templateUrl: '/AngularTemplates/ClientPreferences/DetailsTemplate.html' });                
});

Include preferencesDirective in all templates to keep the directive template consistent while allowing for changing DOM elements in each view's template. By utilizing $routeParams in viewController, you can determine the current route and send appropriate data to the preferencesDirective's controller.

If there is a need to conditionally change the directive's template, ng-include can be used inside the directive's template.

function preferencesDirective() {

    return {
        restrict: 'EA',
        scope:
        {
            factorySettings: '=',
            templateSrc: '='
        },
        controller: 'clientPreferencesController',
        controllerAs: 'pc',
        bindToController: true,
        templateUrl: '<ng-include src="pc.template()"></ng-include>'
    }
}

function clientPreferencesController($scope, $resource, $rootScope, $http, $route, $location) {        
    this.model = @Html.Raw(JsonConvert.SerializeObject(Model));        
    $scope.location = $location.path();     
    $scope.template = function(){
        if($scope.templateSrc) {
            return '/AngularTemplates/ClientPreferences/'+ $scope.templateSrc + '.html';
        }
    }
}

Pass the template source from viewController based on the current route.

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 functionality of my script relies on the presence of an alert function within it

My code seems to only work when I include an alert function in it. I'm trying to make my div scroll to the bottom. I've done some research, but for some reason, the script doesn't run without an alert function. $(document).ready(function ...

Having trouble with the search function in my array, as it is consistently returning false instead of the expected result

Aim: I am working on creating a basic search bar that allows users to input a zip code and matches it with zip codes stored in an array. The objective is to develop a function that can determine whether the entered zip code exists in the array or not, and ...

Having trouble displaying Google Map using GMapPanel in EXTJS 4?

Ext.Loader.setPath('Ext.ux', '../ux'); Ext.require([ 'Ext.tree.*', 'Ext.data.*', 'Ext.window.MessageBox', 'Ext.window.*', 'Ext.ux.GMapPanel' ]); var map = new Ext.ux ...

A Guide to Executing Asynchronous Function Calls in a For Loop using JavaScript

Experiencing issues with asynchronous calls within a for loop in my code. The loop progresses before the async call is completed, causing unexpected behavior. As someone new to this language, I'm trying to understand callbacks and other related concep ...

How can I transfer information from one page to another in Next.js 14 without displaying the data in the URL?

As a React Native developer working on a web app, I'm facing a challenge with passing data from one page to another in Next.js 14 without displaying the data in the URL. I have a specific app directory within my Next.js project. When I mention not sh ...

Struggling to make PayPal Cordova Plugin function properly in both production and sandbox modes

While using the cordova paypal plugin and switching to sandbox mode, I encountered an error. The plugin can be found at https://github.com/paypal/PayPal-Cordova-Plugin https://i.stack.imgur.com/lD2EH.png Running the plugin in PayPalEnvironmentNoNetwork m ...

Locate records through an array of nested references using Moongoose (MongoDB)

Given the collection schema shown below: var terminalSchema = new mongoose.Schema({ name: 'String', ip: 'String' }); var wayPointSchema = new mongoose.Schema({ name: 'String', description: 'String' ...

Issue with Redirecting in React: REST requests are not successful

There's a text input that triggers a submission when the [Enter Key] is pressed. const [ query, setQuery ] = React.useState('') ... <TextField label="Search Codebase" id="queryField" onChange={ event => setQuery( ...

The custom AJAX user control's JavaScript constructor is encountering an "element" that is undefined

I am attempting to develop a customized AJAX user control that includes a client-side object as well. Despite following the guidelines provided in this resource: https://msdn.microsoft.com/en-us/library/bb398906.aspx, I am encountering persistent issues. ...

Accessing WCF REST endpoint using Ajax and transmitting data in JSON format

I have developed a Rest service in WCF (demo), which provides me with the following output: {"GetEmployeeJSONResult":{"Id":101,"Name":"Sumanth","Salary":5000}} Now, I have created an ASP.NET website where I am utilizing AJAX JSON to call this rest service ...

Python/Selenium Issue: JS/AJAX Content Fails to Load when URL is Accessed

Currently, I am attempting to gather data from the following URL: The data that I am looking to extract is loaded dynamically, such as the Center Bore information. When accessing the link through a standard web browser, the content loads without any issue ...

Fill in the missing keys, values, and data within the JSON object

My JSON data consists of various objects with unique dates and site names. The dataset contains distinct dates such as: 2019-10-01, 2019-10-02, 2019-10-03, 2019-10-04, 2019-10-05. Some dates might be missing for certain sites in the dataset. For example, o ...

Guide on transferring Context to the loader in React-Router-6

In my development setup, I am utilizing Context for managing the global loading state and React-router-6 for routing. My approach involves incorporating loader functionality in order to handle API requests for page loading. However, a challenge arises when ...

Organizing Data to Create a D3 Tree Layout from a CSV

My CSV file has the following structure source, target, name, value1 , percentange A1 A1 T1 200 3% A1 A2 T2 340 4% A1 A3 T3 400 2% I want to create a tree diagram similar to this D3 Pedigr ...

Preventing duplicate results in AJAX and SQL

I'm facing an issue with my ajax request and PHP script - when I click the button, the results are duplicating. Here is the HTML AND JS: $("#more-news").click(function(e) { e.preventDefault(); $.ajax({ type: "GET", url: ...

Are there any substitute proxy servers that are capable of bypassing CORS restrictions using local IP addresses?

Successfully bypassing CORS for AJAX requests to public IP addresses using proxy servers has been a game-changer. Is there a similar approach that can be utilized for local IP addresses when the server is hosted off-site? Unfortunately, I lack the abilit ...

The error occurred in Angular with the [dateclass] class specifically within the mat-calendar

I'm currently working on creating a calendar that allows for multiple date selections. I came across a helpful resource on StackBlitz Here is the code snippet for my AppComponent: isSelected = (event: any) => { const date ...

Using Ajax with Angular services

Recently, I decided to explore Angular JS and Async calls as an alternative to $JQuery. However, I encountered a peculiar issue while making ajax calls. To adhere to 'best practices', I shifted my ajax requests to a service and then initiated th ...

Experience the captivating AUTOPLAY feature of the mesmerizing FULLSCREEN SLIT SL

I am currently utilizing a slider that is functioning well, however I am encountering an issue with autoplay. Whenever I click on the navigation arrow or Nav dot at the bottom of the slider, the autoplay feature stops working. For more information, please ...

Secure Flask API used for serving JSON files to a basic HTML, JavaScript, and CSS web application

I have developed a basic web application that will display data in a table and be updated on a weekly basis. To perform this update, I utilize Python code in the backend to scrape and modify data before storing it in a SQLite database. After some researc ...