0

I have wrote a directive called lobInclude, I want the same that ngInclude but with no 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() { }
                };
            }
        }
    }]);

All seems ok but ng-Messages not work correctly when use my directive, you can see here an example: http://codepen.io/jros/pen/jPxmxj?editors=101

In the code pen I have a form with an input and my directive that include a script ng-template that contains other input.

The ng-messages in the first input work fine but not in my include.

Any ideas please?

Sivakumar
  • 1,089
  • 1
  • 13
  • 24
Javier Ros
  • 3,511
  • 2
  • 21
  • 41

1 Answers1

0

The issue is about the compilation of the requested 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));
});

The secuence is: create a element, compile and add/replace the element in the DOM. Debuging angular.js I can see that NgModelDirective is who comunicate with FormDirective controller to set the $pristine, $touch, ... NgModelDirective has a '^?form' as require to comunicate with parent form. Well, when I compile the element the template has no parent form due to that is not included in the DOM. ngModel can't find the ancestor form and can't set $error, $pristine, $touch, ...

The solution is add element to the DOM and then compile 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)
});

Thanks

Javier Ros
  • 3,511
  • 2
  • 21
  • 41