Issue with Ng-Messages not functioning properly due to a custom ng-Include directive lacking a child scope

I have created a custom directive called lobInclude, which is similar to ngInclude but with no isolated scope:

.directive("lobInclude", ["$templateRequest", "$compile", function($templateRequest, $compile)  {
        return {
            restrict: "A", 
            scope: false,
            compile: function()  {
                return {
                    pre: function(scope, elem, attrs) {
                        var toObserve = "lobInclude";
                        attrs.$observe(toObserve, function(value) {
                            value = scope.$eval(value);
                            $templateRequest(value, true).then(function(response) {
                                if (angular.isDefined(attrs.replace))
                                    elem.replaceWith($compile(angular.element(response))(scope));
                                else
                                    elem.append($compile(angular.element(response))(scope));
                            });
                        });
                    },
                    post: function() { }
                };
            }
        }
    }]);

Everything seems to be working fine, however, the ng-Messages are not functioning correctly when using my directive. You can view an example here: http://codepen.io/jros/pen/jPxmxj?editors=101

In the provided code pen, there is a form with an input field and my directive that includes a script with ng-template containing another input field.

The ng-messages in the first input field work properly, but not in the included template.

Any suggestions or ideas on how to resolve this issue?

Answer №1

The problem at hand pertains to the compilation of the specified template:

$templateRequest(value, true).then(function(response) {
    if (angular.isDefined(attrs.replace))
        elem.replaceWith($compile(angular.element(response))(scope));
    else
        elem.append($compile(angular.element(response))(scope));
});

Here's the sequence: create an element, compile it, and then add/replace the element in the DOM. While debugging angular.js, it becomes apparent that NgModelDirective is responsible for communicating with the FormDirective controller in order to set attributes like $pristine, $touch, etc. NgModelDirective requires a '^?form' as part of its requirement for communication with the parent form. The issue arises when compiling the element because the template lacks a parent form since it is not yet included in the DOM. As a result, ngModel cannot locate the ancestor form and therefore cannot set attributes like $error, $pristine, $touch, etc.

The solution involves adding the element to the DOM before compiling it:

$templateRequest(value, true).then(function(response) {
    var responseElem = angular.element(response);
    if (angular.isDefined(attrs.replace))
        elem.replaceWith(responseElem);
    else
         elem.append(responseElem);
    $compile(responseElem)(scope)
});

Thank you

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

Implementing a Vue.js Scrollable Table

I am currently working on a table that is populated using the vue.js v-for method: <table> <tr><th>Name</th><th>Surname</th></tr> <tr v-for="user in users"><td>@{{user.name}}</td><td>@{ ...

Bringing in Vue from 'vue' allows for the incorporation of 'different' Vue to diverse documents

This issue involves the interaction between Webpack, ES6 import syntax, and Vue. Currently, I am working on a Vuex mutation that is responsible for adding a new key-value pair mykey: [] to an object within the state. To ensure reactivity, I need to use Vu ...

Determine the status of caps lock with a single click of a button

I am working on an application that includes a textbox and a button. I need the application to indicate whether the Caps Lock key is activated or deactivated when a user types text in the textbox and clicks the button. ...

Create a unique command that will run regardless of the success or failure of the command before

Even if a preceding command fails, the end command is still executed. For example: browser.waitForElementIsVisible("non-existing-item", 500).end() I am looking to create a custom command that always gets called in the same way as the end command. When I t ...

Is it possible to eliminate the dedupe feature in npm?

By mistake, I accidentally ran the command npm dedupe and now all of my node_modules directories are flattened. While this reduces file size, it's making it more difficult to find things. Is there a way to reverse this and return to the hierarchical f ...

What is the best way to obtain the inner ID with JQuery?

How can I assign values to inside id using JQuery? Sample code from controller.cs: public GroupModel Get() { IGroupTypeRepository groupTypeRepo = new GroupTypeRepository(); IGroupRepository groupRepo = new GroupRepository(); var model = new ...

AngularJS expression utilizing unique special character

There are certain special characters (such as '-') in some angular expressions: <tr data-ng-repeat="asset in assets"> <td>{{asset.id}}</td> <td>{{asset.display-name}}</td> <td>{{asset.dns-name}}</td&g ...

Unable to assign a value to a dropdown using Angular.js and PHP

I am encountering a slight issue with setting the data as a selected value in a dropdown after fetching it from the database. Below is an explanation of my code. plan.html: <div class="input-group bmargindiv1 col-md-12"> <span class="input-g ...

transforming a div to behave similarly to an iframe

I am trying to load content from my page into a div element using the following function: function loadmypage(DIV, pageURL) { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } e ...

Adding HTML content inside an iFrame at a specific cursor position in Internet Explorer

Does anyone know a method to insert HTML into an iFrame specifically for IE? I have been using execCommand insertHtml in Chrome and Firefox, but it doesn't seem to work in IE. I was able to paste HTML into a content editable div using pasteHTML, howe ...

Convert former function to use async and await system

I need to convert this function to async, but I am facing an issue where the users object obtained from mapping interactions is not returning data in the expected format. When I run the async function on the client side, my values are showing up as nil. Th ...

What are some strategies for stopping Knex.js from executing a query object upon return from an asynchronous function?

My node.js backend utilizes Knex.js to construct dynamic DB queries based on various inputs. The challenge I'm facing is handling asynchronous processing of certain inputs. When returning a knex query object from an async function or a Promise resolve ...

Executing a function from a template literal using ng-click in AngularJS

I'm trying to call the close_popup function from within a template literal by passing a variable called id. Here's the code snippet: function register_popup(id, name) { var htmlelement = `<div class="popup-box chat-popup" id="${i ...

Navigating JSON Data with ES6 Iteration

Issue Description There are two APIs I am working with. The first one, let's call it API #1, provides JSON data related to forum posts as shown below: [{ "userId": 1, "id": 10, "title": "Tt1", "body": "qBb2" }, { "userId": 2, ...

How to show a placeholder in a select input using ReactJS

I'm currently trying to incorporate placeholder text into a select input field using ReactJS, but it doesn't seem to be working as intended. Here is the code snippet I am working with: <Input type="select" placeholder="placeholder"> ...

Switching from HTML to BBCode during the editing process

My issue lies in converting BBCode to HTML and then editing the code on a page with AJAX. When editing in a <textarea>, the HTML tags show up instead of the original BBCode. For instance, if I submit [b]bold text[/b] and save it to my database, the ...

Async function is improperly updating the array state by overwriting it completely instead of just updating one item as

I am working on a file upload feature where each uploaded file should have a progress bar that updates as the file gets uploaded. I'm using a state to keep track of selected files and their respective progress: interface IFiles { file: File; c ...

Adjust the x and y coordinates of the canvas renderer

Manipulating the dimensions of the canvas renderer in Three.js is straightforward: renderer = new THREE.CanvasRenderer(); renderer.setSize( 500, 300 ); However, adjusting the position of the object along the x and y axes seems more challenging. I've ...

Error encountered while attempting to obtain OAuth2 API authorization token in ExpressJS Node.js Angular: "getaddrinfo ENOTFOUND"

Recently, I developed an angular application that sends an HTTP post request to a Node/Express.js endpoint upon clicking a button in order to obtain an authorisation token. I successfully configured the necessary credentials for basic OAuth2 authorisation ...

Navigating Users After Form Validation in React - A Step-By-Step Guide

As a newcomer to React, I am currently working on a SignUp SignIn project. My goal is to route the user to the Login/SignIn page upon successful form validation. Below is my SignUp code: import React, { Component } from 'react'; import { Link } f ...