Develop an element by utilizing the scope attribute in Angular

Is it possible to dynamically control a directive's template based on an evaluated $scope variable in Angular?

For instance, the following code may not work as expected due to how $scope is being utilized:

app.directive('inputType', function(){
    var template;

    if ($scope.inputType === 'input') {
         template = "<input ng-attr-my-attribute='" + $scope.myAttribute + "' />";
    }

    return {
        restrict: 'E',
        scope: {
            inputType: '=',
            myAttribute: '='
        },
        template: template
    }    
})

<inputType inputType="input" my-attribute="some value"></inputType>

In this example, the goal is to use a dynamic $scope property to determine the type of HTML element (input, textarea, checkbox, etc) in the directive.

Answer №1

To handle all the conditional markup in your template, you can create the logic based on a two-way bound scope variable from a parent controller. It's important to note that you may not have used your directive correctly in the HTML code. Ensure that you define the directive using camel case and use snake case in your markup. Check out the following example:

DEMO

index.html

<body ng-controller="MainCtrl">
    <input-type-dir  input-type="inputs.one"></input-type-dir>
    <input-type-dir  input-type="inputs.two"></input-type-dir>
    <input-type-dir  input-type="inputs.three"></input-type-dir>
</body>

app.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

    $scope.inputs = {
        one    : 'text',
        two    : 'checkbox',
        three  : 'textarea'
    };

});

app.directive('inputTypeDir', function(){

    return {

        restrict: 'E',

        scope: {
            inputType: '='
        },

        templateUrl: 'template.html'

    }

});

template.html

<input ng-if="inputType !== 'textarea'" type="{{inputType}}">
<textarea ng-if="inputType === 'textarea'" cols="30" rows="10"></textarea>

If you prefer, you can directly access the attributes within the link function without creating an isolate scope if you only need to pass string values:

index

<input-type-dir  foo="text"></input-type-dir>
<input-type-dir  foo="checkbox"></input-type-dir>
<input-type-dir  foo="textarea"></input-type-dir>

directive def

link: function(scope, el, attrs){ 
    scope.foo = attrs.foo;
}

tempalte

<input ng-if="foo !== 'textarea'" type="{{foo}}">

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 are some practical ways to employ optional chaining when working with arrays and functions?

I'm attempting to implement optional chaining with an array instead of an object but I'm unsure how to proceed: Here's my attempt at using it myArray.filter(x => x.testKey === myTestKey)?[0]. I am also experimenting with a similar approa ...

Mall magnitude miscalculation

I am currently experiencing an issue with Galleria and the Flickr plugin. Some images are displaying correctly, while others appear scaled and parts of them are cut off. How can I fix this problem? Below is the HTML code for the Galleria gallery on my web ...

provide a hyperlink to the icon located in front of the navigation bar

I'm struggling to come up with a suitable title for this issue. What I am trying to achieve is placing a small icon in front of the navbar so that visitors can click on it and be directed to another site. Initially, I attempted to place the icon using ...

Node.js encountered an SFTP error stating "Error: connect: An existing SFTP connection is already defined."

Working within my node.js application, I have implemented ssh2-sftp-client to upload an image every 5 seconds. The initial upload functions correctly, but upon repeating the process, I encounter an error message: node .\upload.js uploaded screenshot ...

I am looking to display the results table on the same page after submitting a form to filter content. Can you provide guidance on how to achieve this?

Could someone provide guidance on how to approach the coding aspect of my current issue? I have a search form that includes a select form and a text box. Upon submission, a table is generated with results filtered from the form. Should I utilize a sessio ...

What could have occurred if you reassigned setInterval to a variable within the useEffect hook?

Can multiple setInterval functions be defined repeatedly to the same variable in a React hook useEffect? After checking, I found that the variable has a new setInterval id value every time it is defined. However, I am curious if there are any instances re ...

Exploring ways to verify various types of information in a Postman response

After creating test scripts with the following response data, { "page": 2, "per_page": 6, "total": 12, "total_pages": 2, "data": [ {"id": 7, &quo ...

What is the method for adding up elements based on their identification numbers?

Is it possible to calculate the sum of multiple range sliders using their unique IDs? Multiplying each range slider value by the corresponding input. And finally, adding up all the multiplication results. $(document).ready(function() { $(".range") ...

Executing passport local signup synchronously in Node.js

Struggling to grasp some core concepts within Node.js, particularly in dealing with passport. I'm facing an issue where I need to make a synchronous call to check for email uniqueness before creating a user. If the email is already in use, I want to d ...

Sharing data between parent and child components in React

I am facing an issue with passing a dynamically generated value from child components to my parent/web component. The buttons in the child component are assigned a `value="URL"` based on MongoDB data, and I want to pass that value to my parent component us ...

What is the best way to introduce a time delay between two JavaScript functions?

Here is some JavaScript code that I am working with: clientData.reloadTable( "CreateCSV", "/create/file" ); $("#downloadFrame").attr("src","/download/download"); The first statement in the code above creates a CSV file on the disk. The second statement d ...

7 Tips for Renaming Variables in VSCode without Using the Alias `oldName as newName` StrategyWould you like to

When working in VSCode, there is a feature that allows you to modify variables called editor.action.rename, typically activated by pressing F2. However, when dealing with Typescript and Javascript, renaming an imported variable creates aliases. For exampl ...

Exploring the GET request in Meteor JS

When using Meteor JS, I have a get function set up like this: localhost:3000/profile?user=rishav I am now trying to access the value of user in a Meteor JS template. When dealing with post data, we can use event.target.blah.value; where blah is the id. H ...

Execute the script repeatedly

(Since Stack snippet is temporarily down, I included a jsfiddle link): Visit this link for the code I've been struggling to get this script to work. Here's the simple Javascript code I have: $(document).ready(function() { showMessage(); s ...

It seems like encodeURIComponent is appending an extra character to my string

jQuery.ajax() is behaving strangely when escaping my data. For instance, if I make the following request: $.ajax({ url: 'somethingordinary', data: { name: 'Ihave¬aweirdcharacter'; } }); upon inspecting the XHR in ...

Is JavaScript necessary for this task in PHP?

Hi everyone, I recently discovered a way to style a PHP echo in a more visually appealing manner. Instead of presenting an unattractive colored box right away, I was wondering if there is a way to only display the box when the user selects the calculation ...

Is there a way to link table A's ID to table B's userID in a postgreSQL database?

Is it possible in PostgreSQL to establish a relational index between table A ID and table B userId for the purpose of joining two tables based on their ids? To provide further clarification, here is an example using MongoDB and Mongoose: const Billing = ...

Is adding a property to a div using the Jquery Css Function taking longer than expected?

I am attempting to scale a div when another is clicked, with the scaling origin starting from where the click occurred. This is similar to Apple's behavior when you open an app and it expands from where you clicked. However, I'm facing an issue ...

Difficulty with local storage overwriting

I've been developing a quiz app using only JavaScript. The app allows users to choose a username, answer questions to increase their score, and saves the data in variables. When the game ends, a message is displayed along with the top 5 scores achieve ...

Using jQuery, it is possible to automatically generate a new HTML input element and access it within

My issue is: I am facing a problem with a dynamically generated table on my page using ajax-jquery My table consists of 3 <td> elements: 1 for name and 2-3 for checkboxes representing parameters I have set up an event for all input checkboxes to d ...