Making dynamic changes to AngularJS directive templates during runtime

In my quest to create an input directive that can handle multiple types of inputs (such as Interval (min-max), DateTime, Number, Text...), I've encountered a challenge. It's crucial that when the user changes the data type, the corresponding input template also changes accordingly. Additionally, I need to be able to have more than one input on the page simultaneously (check out PLUNKR for a clearer picture).

After extensive experimentation and research, I've realized that I need to monitor the attribute (great-input), swap out the input template based on the selected input type, and then compile it. However, I'm facing difficulties implementing this in the compile function, and the watches are not functioning properly in the link function (I'm getting t1, t2).

Therefore, my objective is to change the input template upon selecting a different value in the dropdown menu (for simplicity, I've color-coded the various input types).

$scope.$watch('greatInput', function (newVal) {
     console.log(newVal);
     html = getTemplate(newVal);
     $elem.html('').append($compile(html)($scope));
});

This function should essentially do the trick (with some modifications depending on where it's implemented), but I'm struggling to find the right place to integrate it.

For the complete code, visit: http://plnkr.co/edit/BCuiqg?p=preview

Answer №1

If you're looking for a simple solution, one option is to incorporate ng-if statements within the directive template and connect the input type to the scope:

.directive("smartInput", function(){
  return {
    template: '<input ng-if="isStr()" type="txt"    ng-model="smartInputModel">\
               <input ng-if="isInt()" type="number" ng-model="smartInputModel">\
               <input ng-if="isDbl()" type="number" ng-model="smartInputModel">',
    scope: {
      smartInputModel: "=",
      smartInputType: "@",
      // additional properties...
    },
    link: function($scope){
       $scope.isStr = function(){
          return $scope.smartInputType === "5" || someotherCondition();
       }
       // repeat for $scope.isInt and $scope.isDbl
    }
  }
});

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 sequence of text is not appearing correctly

I'm attempting to populate a paragraph with JSON data, while inserting a divider between data gathered on different dates. function fetchAllLogs(employeeId) { $.getJSON('datafile.json', function(data) { $("#" + employeeId).html( ...

Conditional AJAX within the append function

Utilizing an Ajax call to an API, I am retrieving a list of cars along with their specifications within a subset. This information is then displayed in a div using the append function. I have a default_spec_id value which I compare with each car's id. ...

Utilizing a Chrome packaged app to interact with a local sqlite database through reading and writing operations

Is it feasible to access and manipulate a local sqlite database from within a Chrome packaged app? I am currently able to work with a locally stored JSON file for my app data, but now I also require the functionality to interact with a sqlite database in ...

How can I access attribute type information in a Node.js Sequelize model?

I have successfully implemented a model in NodeJS using Postgres and sequelize. Let's say the model is Person and it includes fields for name and age. Now, I am looking to dynamically examine the model class to retrieve details about its attributes, s ...

Protractor - Issue with clicking on hidden element with "ng-click" attribute

I'm facing an issue with a specific element that I am unable to click using Protractor. Everything was working fine until a few days ago. Technical information: Chrome version: 47.0.2526.106 Protractor version: 2.0 Selenium version: 2.44 CSS &l ...

Issue encountered while sending binary data to the server

After attempting to read a local file on the client side and sending it to the server, I encountered an error while trying to retrieve the image. JavaScript let req let rsp async function _post(url,data) { req = await fetch(url,{method: 'POST' ...

Enclose each set of objects, such as text, within a separate div, except for div elements

Is there a way to wrap each immediate group of objects that are not contained in a div with a wrap class? Input: var $code = 'Lorem Ipsum <p>Foo Bar</p> <div class="myclass"></div> <p>Foo Bar</p> <div clas ...

Ensure UseEffect is only triggered once with specific dependencies

Whenever the component is loaded, I have a method called useEffect() that runs once. useEffect(() => { (async function fetchData() { const results = await stateIsoAPI(); setStates(results); // API results to trigger other Use effect ...

Navigating through HTML code - a beginner's guide

I have a variable containing the following HTML code: let htmlDocument = '<div id="buildings-wrapper"> \ <div id="building-info"> \ <h2><span class="field-content">Britney Spears' House</span></ ...

Is it feasible to incorporate a third-party JavaScript file into a React application?

I have a JavaScript file from a previous MVC project that generates a basic table using ExtJS. Currently, I'm working on developing a new React application with a navigation bar and sidebar. My goal is to explore the possibility of importing the exis ...

Mastering the art of managing unchecked and checked checkboxes in Angular 2: A comprehensive guide

I have a code snippet where I want to display the initial state of checkboxes based on the 'initialstatus' array in the UI. I should be able to randomly change the status of any checkbox on the UI, and that change should also be reflected in the ...

The dynamic URL parameters are altered by the Browser's back button

I am currently working on a website where the URL parameter is updated based on user actions. This update triggers changes in the webpage without the need for refreshing. An example scenario would be in an E-commerce site where the URL changes when the use ...

Conceal user input field in React using a hook

I am looking for assistance with a form that has 4 input fields: username, password, email, and mobile. My goal is for the email field to disappear if an '@' symbol is typed in the username field, and for the mobile field to disappear if any digi ...

jquery to create a fading effect for individual list items

I have a group of items listed, and I would like them to smoothly fade out while the next one fades in seamlessly. Below is the code I've been working on: document.ready(function(){ var list_slideshow = $("#site_slideshow_inner_text"); ...

Checkbox remains selected even after the list has been updated

I am currently dealing with an array of objects where each object has a property called "checked." When I click on a checkbox, it becomes checked. However, when I switch to another list, the checkmark remains even though it should not. Here's an examp ...

Encounter a routing issue in Node.js/Express

I am encountering an error Cannot Get / while working on my project, and this is my current folder structure: Below is the content of my route.js file: //route.js 'use strict'; var app = require('../../config/express'); var router ...

Executing a callback function in Swift using JavaScriptCore

Struggling to figure out how to call a Javascript Function with a callback from Swift, but it's not working as expected. Here's what I have: Javascript: global.calculateWithCb = function(temp,cb){ cb(5 * temp) } global.calculate = functi ...

TinyMCE is deleting Bold tags in a numbered list when saving a form

I recently integrated the tinymce editor into one of my textareas, allowing users to format their text with options like bold, underline, and italic. Here is the implementation code: tinymce.init({ branding: false, statusbar: false, resize:true ...

Learn how to default export React with withRouter, all while taking advantage of Material UI's makeStyles

I have been working on integrating Material UI makeStyles with class components, passing useStyles as props while default exporting it in an arrow function. export default () => { const classes = useStyles(); return ( <LoginClass classes={cl ...

Executing a Jquery AJAX request to generate an authorization code

For my project requirement, I need to generate an authorization code by making a call to the O365 URL using jQuery's AJAX function. The script below is being triggered from the document ready() event. $.ajax({ ...