angularjs - Using $setValidity on an element outside of the current scope -
i have global directive, in charge of getting error message controller, compiling, , displaying it.
in case there server validation error such this email exists
, focus on element, , set validity false, e.g. $setvalidity(false)
.
this directive not form, , doesn't contain form.
what suggest (already tried commented out)
directive('messagecompile', function ( $compile, $window, $rootscope ) { return { restrict: 'a', scope: true, link: function ( scope, element, attrs ) { var el; attrs.$observe( 'template', function ( tpl ) { if ( angular.isdefined( tpl ) ) { // compile provided template against current scope el = $compile( tpl )( scope ); // stupid way of emptying element element.html(""); // add template content element.append( el ); } }); attrs.$observe('focus', function(val){ if ( angular.isdefined( val ) && boolean(val)) { var el = angular.element('[name="' + attrs.focus + '"]'); var form = el.parents().find('form'); var formname = form.attr('name'); el.focus(); // scope[formname].$setvalidity(val, false); // el.scope().$setvalidity(false); // scope[formname][val].$setvalidity(false); //$rootscope.scope[formname][val].$setvalidity(false); //$rootscope.scope[formname].$setvalidity(val, false); } }); var windowel = angular.element($window); windowel.on('scroll', function() { if(window.scrolly > 46){ element.parent().parent().addclass('staytop'); // alert('here'); } else{ // alert('here2'); element.parent().parent().removeclass('staytop'); } }); }, } }).
in order use $scope[formname]
controller must on form element. either defining directly:
<form name="theform" ng-controller="thectrl">
or directive:
directive("mydirective", function() { return { template: "<form name='theform'>...</form>", controller: ["$scope", function($scope) { ... }], ... }; });
if 1 these conditions met, have define name attribute every element need access:
<form name="theform" ...> <input name="theinput" ...>
then can access $setvalidity()
, inside corresponding controller, defined above:
$scope.theform.theinput.$setvalidity(false);
again remember: in order controller access form, must @ same element form, or maybe @ child scope.
Comments
Post a Comment