"ng-model not functioning properly with transcluded input"

I have created a simple directive that wraps an input element in a div using transclusion. However, I am facing an issue where it is breaking ng-model for some reason. You can view the full code on this plunker: http://plnkr.co/edit/tYTsVUbleZV1iG6eMgjo

Any ideas on how to fix ng-model functionality?

Directive Script

Below is the script for the directive:

testapp.directive('wrapInput', [function () {
   return {
      replace: true,
      transclude: 'element',
      template: '<div class="input-wrapper" ng-transclude></div>'
   };
}]);

Answer №1

By adjusting your HTML markup like so:

<div  wrap-input>
  <input type="text" ng-model="anObject.anotherValue"/>
</div>

In addition, you can utilize:

transclude: true // instead of transclude: 'element'

Everything should function correctly with this modification. While I cannot provide an exact explanation, I have encountered similar issues in the past when combining transclude: 'element' and replace: true. Further investigation into the source code may shed light on the issue. Nevertheless, the end result with this workaround should remain consistent.

Answer №2

Upon discovering the capabilities of ng-repeat, I was convinced that it had to be achievable:

http://plnkr.co/edit/stf02iPNvNnlsx1dsFZx?p=preview

app.directive( 'wrapThisThing', [ '$compile', function( $compile ) {
  return {
    restrict: 'A',
    transclude: 'element',
    link: function( scope, element, attrs, ctrl, transclude ) {

      // Creating a new DOM context and binding it to the scope.
      var template = angular.element( '<div class="wrap">' );
      var context = $compile( template )( scope );

      transclude( function( clone, theScope ) {
        // In order for this to work properly, we must remove the directive attribute from the cloned element
        // before compiling it back to its original scope. Failure to do so would result in an infinite loop.

        // By utilizing the $attr property, we can determine which attribute variant was used (e.g., data-wrap-this-thing, x-wrap-this-thing).
        // For more information on attribute normalization, refer to:
        // http://www.bennadel.com/blog/2648-inspecting-attribute-normalization-within-directives-in-angularjs.htm

        clone.removeAttr( attrs.$attr.wrapThisThing );

        // Compile the transcluded element and bind it to its own scope, then append it to our new context.
        context.append( $compile( clone )( theScope ) );
      });
      element.replaceWith( context );
    }
  };
}]);

Answer №3

To make your directive work, you need to set up an isolated scope and possibly a controller. Here is an example of how you can achieve this:

return {
  replace: true,
  transclude: 'element',
  scope: {},
  controller: function(scope){},
  template: '<div class="input-wrapper" ng-transclude></div>'

};

After setting up the isolate scope and controller, you just have to bind the directive's scope to the parent scope. I'm currently unable to get it to work in your plnkr, but I will update my answer once I do.

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

Exploring trees with jQuery: A guide to traversal techniques

<ul id="org" style="display:none"> <li id="visited"><a href="#" class="ui-link">ROOT</a> <ul id="main_child_ul" class="children"> <li><a href="#">Acura</a> & ...

Exploring the functionality of $.param in jQuery

After extensive research online, I found that the most helpful information was on the official jQuery site. Here is the code snippet I am currently using: var param = { branch_id : branch_id}; var str = $.param(param); alert(str); However, when I log or ...

What is the best way to save a current HTML element for later use?

Here is a simple HTML code that I would like to save the entire div with the class test_area and then replicate it when needed. Currently, my goal is to duplicate this div and place the clone underneath the original element. How can I achieve this? Unfortu ...

Is it feasible to save the outcome of a function call using ng-repeat?

Looking for a solution with the following code: <tbody ng-repeat="term in Items | filter:searchText track by term.Element"> <tr class="term-row"> <td ng-show="!IsValid(term)" class="text ...

Encountering a VueJS error with Google Cloud Logging Winston: "TypeError: The 'original' argument must be a Function."

I have been attempting to integrate @google-cloud/logging-winston into my VueJS project by closely following the guidelines provided in both the npm package and Google Cloud docs. However, I am encountering an error message stating "TypeError: The &q ...

Once the puppeteer infinite scroll has completed, it fails to retrieve all the available results

Below is the code snippet from my data scraping file: const puppeteer = require('puppeteer'); const db = require('../db'); const Job = require('../models/job'); (async() => { try { const browser = await puppetee ...

Retrieve information from an ajax request without relying on the asynchronous option

I'm relatively new to working with JavaScript and ajax, and I've encountered some confusion regarding the data/success returns in ajax. Below is the ajax code I've been using. My goal is to execute the code within success: once the json res ...

Can you point me towards the location of Sigma.js' sigma.utils.xhr() function?

I came across a peculiar issue with lines 23 and 24 of sigma/plugins/sigma.neo4j.cypher/sigma.neo4j.cypher.js: sigma.neo4j.send = function(neo4j, endpoint, method, data, callback) { var xhr = sigma.utils.xhr(), Surprisingly, sigma/src/utils/sigma.uti ...

When data is stored in Internet Explorer's cache, any changes made are not being reflected in

Internet Explorer stores data in cache and even if there are changes, it may not reflect onclick. However, when I open the developer mode and try to access the same, then it works perfectly. This issue only seems to occur in IE as all other browsers work f ...

Leveraging personalized design elements from a theme in Material UI without the need for makeStyles

Is there a way to access the theme.customElements.actionButton in MyComponent without relying on makeStyles? For instance, can I directly use className={theme.customElements.actionButton}? theme.js const theme = createMuiTheme({ customElements: { ...

Struggling with the task of assigning a glTF item to a separate layer within Three.js

Exploring the use of layers in Three.js. This script includes a sphere, a triangle, and a glTF object (car). I activated a second layer: camera.layers.enable(1); Assigned the sphere, triangle, and glTF object to layer 1: car.layers.set( 1 ); sphere.lay ...

An unexpected punctuation token «(» was encountered instead of the expected punctuation when generating a chunk using UglifyJS

I encountered an error while attempting to perform a production build using webpack version 2.2.1: > cross-env NODE_ENV=production webpack --config internals/webpack/webpack.prod.babel.js --color -p --progress Hash: 7bb2cdb98aab2f36f7e1 ...

Ways to cease a setInterval after a specified duration or a specific number of iterations

I have successfully implemented a jQuery code for creating a loop of "changing words" by referring to the solution provided in this Stack Overflow answer: jQuery: Find word and change every few seconds My question is, how can I stop this loop after a cert ...

Updating a controller variable in Angular after calling an $http service

Trying to wrap my head around the different blogs and examples regarding the proper usage of promises in Angular. It would be really helpful if someone could provide some clarity on this topic. Is it considered incorrect to use a callback passed into the ...

Guide on eliminating lines that start with a particular character

I need help figuring out how to remove all lines of code that start with #include. Here's an example: #include 'utils/namespace.js' #include 'utils/constants.js' #include 'utils/helpers.js' #include 'utils/json2.js& ...

Issue with calling on-click function from a directive's template not being triggered

I am new to Angular and I'm experiencing an issue with my ng-click not working in certain contexts. Let me share my code and explain the problem more clearly. HTML : <div ng-app='myApp'> <section id="map-orders" ng-controller= ...

Utilizing tag keys for inserting text and adjusting text sizes within a Web application

Creating an online editing interface for coursework where keyboard events are used. The goal is to have the tab key insert text, while also reducing the size of the text on that line. However, upon using getElementById, an error message pops up stating: ...

Ways to update a value in a table by comparing two JSON objects

I am currently working with two JSON files containing data as shown below: JSON 1: let classes = [{ "Class": "A", "as_of": "12/31/2020", "student": [{ "raji": { "eng": ...

How can I retrieve the text input from a physical barcode scanner in a React Native screen?

Currently, I am developing a mobile application with React Native version 0.68.2. I am seeking a solution to detect barcode scanning events from a physical scanner hardware that is integrated into the mobile device as a handheld scanner. The key requirem ...

When certain triggers are activated, a hidden textbox revealed through javascript is made visible

After changing a dropdown value (from ddlSource) and hiding some text boxes using JavaScript, everything works fine. However, when the user enters a certain value in another textbox triggering an AJAX call to populate some labels, upon form reload, the hid ...