angular.js icon indicating copy to clipboard operation
angular.js copied to clipboard

dynamic element validation

Open hyusetiawan opened this issue 14 years ago • 235 comments

I have a problem with validating inputs that are generated dynamically. Here is the fiddle that shows the problem: http://jsfiddle.net/flsilva/8JzDb/17/

this is taken from: https://groups.google.com/forum/?fromgroups=#!topic/angular/qLeUWZVuQMI

the name is generated fine but it's not bound to the form scope. Because I can name it correctly but the form is not bound, it seems that this behavior is inconsistent.

Thoughts?

hyusetiawan avatar Sep 21 '12 22:09 hyusetiawan

+1

ghost avatar Apr 19 '14 23:04 ghost

+1 Thank you @caitp and @Thinkscape for your workaround

dschu012 avatar Apr 22 '14 19:04 dschu012

+1

TheDom avatar Apr 25 '14 12:04 TheDom

+1 I too thank @caitp and @Thinkscape for your workaround.

daric81 avatar Apr 25 '14 15:04 daric81

Hello, I 've got a solution for ng-form dynamic names :

It doesn't work with input's, only with the ng-form directive :

In angualrjs source code, replace

function FormController(element, attrs) {

by

function FormController(element, attrs, scope) {

and

 form.$name = attrs.name || attrs.ngForm;

by

if(typeof scope.$eval( attrs.name ) !== 'undefined'){
    form.$name = scope.$eval( attrs.name );
}
else{
    form.$name = attrs.name || attrs.ngForm;
}

and

 alias = attr.name || attr.ngForm;

by

 if(typeof scope.$eval( attr.name ) !== 'undefined'){
       var alias = scope.$eval( attr.name );
 }
 else{
      var alias = attr.name || attr.ngForm;
 }

Now in your template, you can do :

<form name="MainForm">
     <div ng-form name=" dynname ">
         <button type='button' ng-click='testt(dynname)'>Submit</button>
     </div>
</form>

And in your controller :

$scope.dynname = 'myForm';
$scope.test = function(formName){
    console.log($scope.MainForm[formName];
}

to access, and modify your form's properties.

a-lucas avatar Apr 27 '14 08:04 a-lucas

well, not quite =) $scope.$eval() won't take interpolation markers into account, so it would actually be name="dynname" without the curly braces.

This isn't totally desirable, though, because you can get unexpected results with non-string properties of scope which you inadvertently use in your template.

caitp avatar Apr 27 '14 08:04 caitp

Exactly right , Interpolation.. I didn't knew this word before ..

I was testing it while writing this post. Thank you for reminding me to edit my post above.

This understand it isn't very appropriate to edit a framework source code like this, but I spent so much time with this validator provider.

I will check if this is possible to implement the same on the input directives as well.

More later.

a-lucas avatar Apr 27 '14 09:04 a-lucas

@caitp To force all inputs to support a dynamic name, I found out that modifying slightly the NgModelController in 1.2.9 resolves the issue for me :

in the definition of NgModelController, replacing

this.$name = $attr.name;

by

if(typeof $scope.$eval($attr.name) !== 'undefined'){
    this.$name = $scope.$eval($attr.name);
}
else{
   this.$name = $attr.name;
}

This solves the issue. The name attribute will be interpolated.

If we want to support as well a dynamic change of this input's name, some work needs to be done. But basically, a $watch in the ngModelDirective function would fix it : (This code is untested).

$scope.$watch('attr.name', function( newValue, oldValue){

     if(typeof $scope.$eval(newValue) !== 'undefined'){
         var oldName = $scope.$name;
         $scope.$name = $scope.$eval(newValue);
     }
     else{
        if(typeof newValue === 'undefined' || newValue=='' || typeof newValue=='integer'){
             throw "Some probleme here mate...";
        }
        var oldName = $scope.$name
        $scope.$name= newValue;
     }

    if(formCtrl){
         delete(formCtrl[oldName]);
         formCtrl.$addControl(modelCtrl);
    }
 }

}

a-lucas avatar Apr 27 '14 09:04 a-lucas

you might think that, but it turns out you're wrong in this case! $scope.$eval($attr.name) will never perform interpolation, at all. Not even once! It evaluates the expression, which is something the $interpolate service also does, but $interpolate makes sure to stringify everything, and always returns a string.

I mean, if it works for your purposes then by all means do it, but it's not an ideal solution, because of the pitfalls of $eval and the weird bugs that it can introduce when used on something that is expected to always be a string literal and not an expression.

caitp avatar Apr 27 '14 09:04 caitp

@caitp I obviously need to go deeper in angularjs source code.

Thank you for this clear explanation.

a-lucas avatar Apr 27 '14 09:04 a-lucas

Nested forms are not a proper solution, but a hack to get things working.

And I also want to print the validation messages at the top of the main form. How can I do this with nested forms and all input elements having name="input"

+1 for a fix in the core.

lderks avatar Apr 28 '14 14:04 lderks

I've had problems with @Thinkscape decorator when it was uglified so I fixed it.

Here's the solution:

$provide.decorator('ngModelDirective', ["$delegate", function($delegate) {
    var ngModel = $delegate[0];
    var controller = ngModel.controller;

    ngModel.controller = ['$scope', '$element', '$attrs', '$injector', function(scope, element, attrs, $injector) {
        var $interpolate = $injector.get('$interpolate');
        attrs.$set('name', $interpolate(attrs.name || '')(scope));
        $injector.invoke(controller, this, {
            '$scope': scope,
            '$element': element,
            '$attrs': attrs
        });
    }];

    return $delegate;
}]);

$provide.decorator('formDirective', ["$delegate", function($delegate) {
    var form = $delegate[0];
    var controller = form.controller;

    form.controller = ['$scope', '$element', '$attrs', '$injector', function(scope, element, attrs, $injector) {
        var $interpolate = $injector.get('$interpolate');
        attrs.$set('name', $interpolate(attrs.name || attrs.ngForm || '')(scope));
        $injector.invoke(controller, this, {
            '$scope': scope,
            '$element': element,
            '$attrs': attrs
        });
    }];

    return $delegate;
}]);

Thanks @Thinkscape ;)

2fdevs avatar Apr 30 '14 13:04 2fdevs

@2fdevs no probs mate :-)

Btw: what did you change ? I don't see it ... I've incorporated the fix in all my apps and they are all compiled (minified). My original code works fine with minification... unless I'm missing something.

Thinkscape avatar Apr 30 '14 13:04 Thinkscape

I've added ["$delegate" in this lines.

$provide.decorator('ngModelDirective', ["$delegate", function($delegate) { ...
$provide.decorator('formDirective', ["$delegate", function($delegate) { ...

@Thinkscape the solution worked perfect for me but when I was testing with minified files karma tests throw me a few errors, so maybe it's only a problem with minified files and karma.

2fdevs avatar Apr 30 '14 13:04 2fdevs

+1

catalin-enache avatar Apr 30 '14 13:04 catalin-enache

Thanks, I've fixed my fiddle.

Updated workaround with demo: http://jsfiddle.net/23RPt/

Thinkscape avatar Apr 30 '14 13:04 Thinkscape

Works for me, using ng-repeat:

<div ng-repeat="field in user.fields">
  <input name="fields.{{$index}}">
</div>

My form now has fields.0, fields.1, etc.

mattcasey avatar May 01 '14 17:05 mattcasey

+1

bluerabbit avatar May 06 '14 12:05 bluerabbit

This is not entirely straightforward. One of the main drivers behind not allowing dynamic name attributes on input elements in Angular 1.0 and 1.2 was that changing the name attribute of an input element doesn't work very well in IE. See http://msdn.microsoft.com/en-us/library/ms534184(v=vs.85).aspx

It seems that <IE8 is totally bust (but we don't support those versions anyway), IE8 and IE9 seem progressively better (IE8 is not supported by Angular 1.3) but I am not sure that IE9 fully supports changing the name.

It may well be that for Angular applications we don't really care about the IE9 oddities but they should be clearly evaluated and documented before we can implement any such strategy.

petebacondarwin avatar May 08 '14 18:05 petebacondarwin

We have a version of @caitp's code running perfectly on IE9, though that may have no bearing on whether the ultimate solution will work as well.

mendelk avatar May 08 '14 19:05 mendelk