Skip to content

Instantly share code, notes, and snippets.

@Nate-Wilkins
Created November 18, 2014 19:19
Show Gist options
  • Save Nate-Wilkins/deab07958f250d0cfb07 to your computer and use it in GitHub Desktop.
Save Nate-Wilkins/deab07958f250d0cfb07 to your computer and use it in GitHub Desktop.
Angular isolate form

Taken directly from: http://jsfiddle.net/gikoo/qNrFX/

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


demoApp.controller('nestedFormIsolation', function ($scope) {
    $scope.setPristine = function(form){
		form.$setPristine();
	};
});

demoApp.directive('isolateForm', [function () {
    return {
        restrict: 'A',
        require: '?form',
        link: function (scope, elm, attrs, ctrl) {
            if (!ctrl) {
                return;
            }

            // Do a copy of the controller
            var ctrlCopy = {};
            angular.copy(ctrl, ctrlCopy);

            // Get the parent of the form
            var parent = elm.parent().controller('form');
            // Remove parent link to the controller
            parent.$removeControl(ctrl);

            // Replace form controller with a "isolated form"
            var isolatedFormCtrl = {
                $setValidity: function (validationToken, isValid, control) {
                    ctrlCopy.$setValidity(validationToken, isValid, control);
                    parent.$setValidity(validationToken, true, ctrl);
                },
                $setDirty: function () {
                    elm.removeClass('ng-pristine').addClass('ng-dirty');
                    ctrl.$dirty = true;
                    ctrl.$pristine = false;
                },
            };
            angular.extend(ctrl, isolatedFormCtrl);
        }
    };
}]);
@ParmanBabra
Copy link

I have found some problems in the variable of rootscope controller I use is not available anymore. how can i do?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment