Struggling to implement dynamic templates in an Angular directive

In the process of developing a small angular application that consists of 3 modes - QA, Production, and Sandbox. In the QA mode, there are multiple buttons for users to select values which then populate "myModel". The other two modes, Production and Sandbox, have buttons next to them to apply the previously selected QA value from myModel using the sync function.

I have implemented different templates for QA (multiple buttons) and Production/Sandbox (single button to sync from QA-myModel). While I am able to render the QA/Production template successfully, the QA template (list of buttons) is not displaying at all.

I suspect there may be an issue with how the compilation is occurring for the list of buttons.

For reference, please check out the code here: http://jsbin.com/sutipo/1/watch?html,js,output

The HTML & Directive used to dynamically select templates are as follows:

    <tr>
        <td> <strong>Production : </strong>  </td>
        <td> {{types.production.text}} </td>
        <td><app-typedisplay env="production" status="non-base"></app-typedisplay></td>
    </tr>
    <tr>
        <td> <strong>SandBox : </strong>  </td>
        <td> {{types.sandbox.text}}  </td>
        <td><app-typedisplay env="sandbox" status="non-base"></app-typedisplay></td>
    </tr>
    <tr>
        <td><strong>QA : </strong>
        <td> {{types.qa.text}}  </td>
        <td><app-typedisplay env="qa" status="base"></app-typedisplay></td>
    </tr>

And the directive :

app.directive('appTypedisplay', function ($compile) {

    var getTemplate = function (content) {
        var template = '';
        var base = "<button type='button' class='btn btn-default' " +
            "ng-class='{active: option.text == model.text}'" +
            "ng-repeat='option in options' " +
            "ng-click='activate(option)'>{{option.text}} " +
            "</button>";

        var non_base = "<td> <button " +
            'ng-click=\'sync("' + content.env + '")\'>' +
            "Sync to " + content.env + "</button> </td>";

        switch (content.status) {
            case 'base':
                template = base;
                break;
            case 'non-base':
                template = non_base;
                break;
        }

        return template;
    };

    var linker = function (scope, element, attrs) {
        element.html(getTemplate(attrs));
        $compile(element.contents())(scope);
    };

    return {
        restrict: 'E',
        scope: {
            model: '=',
            options: '=',
            env: '='
        },
        controller: function ($scope) {
            $scope.activate = function (option) {
                $scope.model = option;
            };
        },
        link: linker
    };
});

As a newcomer to Angular, I would appreciate any help in understanding why the list of buttons template is not compiling correctly.

The expected output should resemble something like the following:

Answer №1

You have specified certain attributes to be transferred to your directive's isolated scope, however you forgot to include the actual model references:

<app-typedisplay area="testing" state="default" settings="settings" data="myData"></app-typedisplay>

The isolated scope of the directive operates independently from its parent scope, therefore all data must be explicitly passed through attributes.

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

Extract the image URL from a JSON API

I'm struggling to retrieve an image URL from a Wordpress JSON API and populate an image tag with it. Below is the code that isn't working for me: $(document).ready(function() { $.getJSON('http://interelgroup.com/api/get_post/?post_id=46 ...

Guide to Increasing Table Index within Nested Loop in Vue.js 3

How can I increment table indices within a nested loop in Vue.js 3? I am currently working with two-level deep arrays using Vue.js, and I need an index that starts at 1 and increases for each item in the top-level array. The desired output is as follows: ...

How come my RXJS next method is being invoked before the $digest cycle is completed, and what is the best way to wait for it to

Below is a code snippet written in Coffeescript: beforeEach "We should see the list changed event", (done) -> constructorSubscription = importList.onListChanged().subscribe -> # Expects constructorSubscription.unsubscribe() ...

Tips for transferring canvas information from JavaScript to Django using Ajax

Currently, I'm developing a Django application that allows users to activate their webcams and capture photos. These images are stored in a canvas, and my goal is to send this image to Django views so that it can be saved on the server. To trigger th ...

Using the moment library in Angular to convert date and time can sometimes lead to errors

Whenever I attempt to convert a Gregorian date to a Persian date, the minute value in the conversion ends up becoming an error. For instance, let's say I want to convert this specific date and time to a Persian date: 2020-09-14T16:51:00+04:30 should ...

Exploring React-Query's Search Feature

Looking for guidance on optimizing my Product search implementation using react-query. The current solution is functional but could be streamlined. Any suggestions on simplifying this with react-query would be greatly appreciated. import { useEffect, use ...

Integrate an external script with React and initialize a new instance

I've been working on integrating a neat canvas background feature from this GitHub project into my React web application. Here's what I've attempted: import {WarpSpeed} from './warpspeed.js' import WarpSpeed from './warpspee ...

Achieving the retrieval of all data can be done simply by utilizing the `echo json_encode($data);

I am trying to automatically update the user wall with new data from the database using a script that checks for updates every 15 seconds. Everything works fine when I only use one piece of data like $data = $row['description']; in the server.ph ...

Having trouble resolving this technical problem in Express.js and JavaScript programming

try { console.log('11111') const { data: { tasks }, } = await axios.get('/api/v1/tasks') console.log('22222 ' + await axios.get('/api/v1/tasks') ) console.log('33333 ' + tasks) https://i.sstatic.net/mLLV ...

Can media queries styles be applied to a window of random size using JavaScript?

Can JavaScript be used to apply media queries style based on random window sizes? I have 5 buttons that I want to switch styles for using JavaScript according to the media queries defined in my CSS stylesheet. Is there a method to achieve this? ...

Open the CSV document

Why am I receiving an error stating ./vacancy-data.csv cannot be found when attempting to pass the csv file into the csvtojson npm package? The csv file is located in the same directory as the code below: var express = require('express'), route ...

Failed commitments in Protractor/WebDriverJS

WebdriverIO and Protractor are built on the concept of promises: Both WebdriverIO (and as a result, Protractor) APIs operate asynchronously. All functions return promises. WebdriverIO maintains a queue of pending promises known as the control flow to ...

Tips for handling the final row of a CSV file in Node.js with fast-csv before the 'end' event is triggered

After using fast-csv npm, I noticed that in the code provided below, it processes the last row (3rd row) of CSV data only after triggering the "end" event. How can this issue be resolved? ORIGINAL OUTPUT : here processing request here processing re ...

Interactive Geography Selector

When updating your personal details on , you are required to choose your country first. Once the country is selected, the system automatically adjusts the city and/or state options based on that specific country's requirements. Can someone provide exa ...

Unlocking the data within an object across all Components in Vue

Recently, I've started using Vue and encountered a problem. I'm trying to access data stored inside an Object within one of my components. To practice, I decided to create a cart system with hardcoded data for a few games in the app. Below is the ...

The JSON response may be null, yet the data flows seamlessly to the success function in

Currently, I am facing an issue with Ajax. The situation is as follows: I want to check if a user is available by typing their email address. Therefore, I have created a JavaScript function that includes an Ajax script for this purpose. Here is my code: $ ...

I possess a primary menu with several submenus, yet I am encountering difficulty accessing the submenus. My goal is to efficiently navigate and access the appropriate submenu within the main menu

I am facing an issue with my CSS where the sub menu is currently showing from the left side, but I would like it to slide up and down instead. .outer { width: 100%; text-align: center; background-color: Gray; padding-top: 20px; bord ...

How can I resolve the issue of <td> being repeatedly displayed five times instead of just twice in PHP?

Can someone assist me with fixing this for loop issue? I am trying to display controls next to each item in the row, but it is showing 5 sets of controls instead of just 2. <tbody> <?php //retrieve list of supplies $numOfRows = 0; $result = my ...

There seems to be an issue with accessing the Angular module, even though it has been clearly

While attempting to execute the code below, two errors are encountered: Error: [$injector:nomod] Module 'rooms' is not available! The module name is spelled correctly and loaded dependencies have been included. The modules are structured in the c ...

Understanding the $scope array and the use of $scope.$apply in AngularJS is

I'm currently diving into the world of AngularJs and encountering an issue that needs addressing. My goal is to display an array of items within a view. Initially, in the controller, I set up the array using $scope.arrName = [], then proceed to acqui ...