Dynamically update Angular directives with a new template

One of the controllers I created has some variables:

.controller('DataProvider', function($scope, $timeout, $mdSidenav, $mdDialog, $mdMedia, $mdToast, selectedData) {
    $scope.provider;
    $scope.providers = [{
        name: 'jsonProvider',
        displayNmae: "jsonProvider"
    }, {
        name: 'imageProvider',
        displayNmae: "imageProvider"
    }];
    $scope.props = {
        id:_guid(),
        provider:''
    }
    this.providerWasChange = function() {}
})

This is just a small part of the controller's functions. The $scope.props is a model from JSON data.
There is also a directive that is supposed to take the controller's selected provider and change the template, while also possibly binding all $scope.props to the updated template.
Here is my failed attempt at creating the directive:

.directive('provider', function([$compile, $templateCache, function($compile, $templateCache) {
    var getTemplate = function(data) {
        function templateId() {
            switch (data.name) {
                case 'jsonProvider':
                    return 'jsonProvider-template.html';
                case 'imageProvider':
                    return 'imageProvider-template.html';
            }
        }

        var template = $templateCache.get(templateId(data));
        return template;
    }

    return {
        templateUrl: '',
        transclude: true,
        scope: {
            provider: '@'
        },
        replace: true,
        restrict: 'E',
        require: '?NgModel',
        link: function(scope, element) {
            var template = getTemplate(scope.$parent.provider)
            element.html(template)
            $compile(element.contents())(scope)

            scope.$parent.$watch(function() {
                return scope.$parent.provider;
            }, function(newVal, oldVal, scope) {
                console.log(newVal)

                var template = getTemplate(scope.$parent.provider)
                element.html(template)
                $compile(element.contents())(scope)


            })
        }
    }
}]))

Here is the HTML code:

<md-tab id='layerProviderWrapper'>
                            <md-tab-label>Provider data</md-tab-label>
                            <md-tab-body>
                                <div layout="column" ng-controller="layerProvider">
                                    <md-input-container style="width:90%">
                                        <label>Choose provider data</label>
                                        <md-select ng-model="provider" ng-change="providerWasChange()">
                                            <md-option><em>None</em></md-option>
                                            <md-option ng-repeat="provider in providers" ng-value="provider">
                                                {{provider.displayNmae}}
                                            </md-option>
                                        </md-select>
                                    </md-input-container>

              problems starts here:  <provider> </provider>

                                </div>
                            </md-tab-body>
                        </md-tab>

The template should take ng-models from the 'DataProvider' controller. I have seen similar questions on StackOverflow, but none of the solutions worked for me...

https://jsfiddle.net/0jLt0u0L/2/ provides an example, but I am unsure how to create a template there. In the template, I want to display the selected provider from the controller.

Answer №1

Check out the adjustments made to your fiddle to ensure functionality to some degree: https://jsfiddle.net/masa671/77z165uj/

Highlighted modifications include:

  • Placing angular.min.js at the beginning.
  • Moving ng-appto the body to optimize the templates (refer to HTML gear).
  • Defining templates through <script> tags.

Instead of loading templates via $http (potentially not feasible on jsfiddle), they were directly defined on the page. For instance:

<script type="text/ng-template" id="jsonProvider.html">
  <div>I am a jsonProvider.</div>
</script>

Once initial functionality is achieved, further customization like dynamic loading with $http can be explored if necessary.

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

Sequentially run jQuery functions

function functionOne() { $('#search-city-form').trigger('click'); } function functionTwo() { $("form input[name='tariffId']").val("137"); $('#search-city-form').trigger('click'); } function funct ...

Having trouble deploying my Express/Next app on Netlify

I am facing issues deploying my Next/Express app on Netlify. While the app functions perfectly locally, I encounter problems when attempting to deploy it using Netlify lambda function. Here are the links to my test git repositories: https://github.com/La ...

Applying a consistent script with varying inputs on the same HTML page

Is it possible to create a JavaScript code that can be used across different sections of an HTML document? The goal is for the script to fetch data such as title, runtime, and plot from a specific URL request and insert this information into the appropriat ...

What could be causing the props to appear empty in a Child component within a Quasar framework and Vue 3 application?

I am facing an issue while passing props to a Child component table in my Quasar Vue3 app. The content is not being rendered, and I can't figure out why. Strangely, the console is clear of any errors. In the parent component, I am creating an object w ...

Issue with Ionic's refresh button functionality

On one of my pages, I have a refresh button that populates a table with JSON data. The data is cached and then displayed on the view. Now I'm looking for a way to refresh the page using Ionic. Any help would be greatly appreciated. Thank you! ...

Whenever the click event is triggered, Ajax is making numerous duplicate calls

Each time I click to fetch my content using an AJAX call, the calls end up duplicating themselves. I've tried various on-click events I came across on Stackoverflow threads, but unfortunately none of them seem to be solving the issue. $(document).rea ...

Looking for a more efficient method to pass components with hooks? Look no further, as I have a solution ready for

I'm having trouble articulating this query without it becoming multiple issues, leading to closure. Here is my approach to passing components with hooks and rendering them based on user input. I've stored the components as objects in an array an ...

Why is 'this.contains' not recognized as a function when I invoke it within another function?

While attempting to create a Graph and incorporating one method at a time, I encountered an issue. Specifically, after calling a.contains("cats"), I received the error '//TypeError: Cannot read property 'length' of undefined'. Could thi ...

What is the best way to create a unit test for a function that calls upon two separate functions?

When testing the getAppts function within this module, the correct way to evaluate the code it encompasses may not be entirely clear. Should db.getDatabase() and fetchAppts() be run as stubs inside the unit test function? The current unit test implementati ...

Calculating the total sum of values using a dropdown list as a filter with J

I have successfully implemented a dropdown filter in my jQuery datatable to filter data. However, I am now looking to calculate the sum of all values in the filtered table each time a user selects a value from the dropdown list. How can I achieve this? My ...

There seems to be an issue with the $scope variable not being properly updated within the function in

<button class="button button-primary" ng-click="updateSchedule(controlCenter.selected)"> Update Schedule </button> Calling the updateSchedule function from the button $scope.data = []; $scope.updateSchedule = function(selectedData) ...

The identity of the provider remains a mystery: $$MapProvider

Encountered an issue with an Unknown provider: $$MapProvider <- $$Map <- $$animateQueue <- $animate <- $compile <- $$animateQueue Experiencing the Unknown $$MapProvider Error When Utilizing the 'angular-animate' Module The conten ...

Tips for Repurposing a React Table

I am in the process of developing my own react component library to be used across my entire application. At the moment, I have started with a table component which is currently undergoing testing. However, I am facing the challenge of calling the componen ...

Updating the value of each preceding sibling of every checked checkbox using jQuery upon form submission

After extensive research, I discovered that the most effective approach involves using a clever workaround to capture every tick and untick on a dynamic input row with multiple checkbox arrays. However, none of the solutions provided a viable method. I th ...

Reducing the size of textures in three.js

Is it possible to shrink the faces of a model rendered in the browser using Threejs, without affecting the mesh structure? I am looking for suggestions on how to accomplish this unique task. ...

Leveraging HTML tables for input purposes

Just starting out with php, HTML, and mysql. Using HTML tables for the first time here. Created an HTML table filled with data from a MySQL table. Planning to use this table as a menu where users can click on a cell with a specific date. The clicked date ...

Angular - transform expression result using specific values

I am attempting to modify the output of an expression based on a set of options stored in an object. Currently, I have an expression {{ resultItem.OdometerUnit }} that can result in one of three variations: hours kilometers miles My goal is to first ch ...

How to Handle Tab Navigation on a Mobile Website without Javascript?

My website primarily targets mobile devices, with tabs in the top navigation. Currently, these tabs are hard coded instead of utilizing Javascript. We want to ensure our site is accessible on all mobile devices, including those without Javascript support. ...

Reverting changes in an Angular directive

Initially, I created a directive that receives an object via bindToController for editing. Everything worked well until I needed to cancel an edit. To undo the changes, I had to create a duplicate of the original object, make changes to it, and then either ...

Having difficulty in dynamically loading an image from an API's URL in Angular

In the title, I mentioned that I am utilizing a free API to display cryptocurrency news for my practice project. Everything seems to be working fine except for displaying the images in card view. I will share my code here, so if you have any suggestions on ...