0

I'm trying to create a bunch of reusable components, which are mainly form controls.

For this reason, I believe (Maybe there is a different approach for this?) I need to create dynamic names for the ng-form directive so that it won't overwrite another ng-form in the same scope.

The problem is that I'm not able do validation since expressions aren't working with ng-messages.

Below is a very simplified demo (sorry about the long template string, couldn't find a better way to add it in stacksnippets), with just one instance of directive and no other parent scopes. But in real scenario those will be there, so I'm creating form name dynamically.

angular.module('test', ['ngMessages'])
  .directive('formGroup', function() {
    return {
      scope: {
        classList: '='
      },
      replace: true,
      template: '<div class=\"container\" ng-class=\"classList\" ng-form=\"fg_{{$id}}\"><input type=\"text\" name=\"testInput\" ng-model=\"testValue\"  required><div ng-messages=\"fg_$id.$error\"><p ng-message=\"required\">Something is wrong!<\/p><\/div><\/div>'
    }
  });
div.container {
  height: 100px;
  padding: 5px;
  border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular-messages.js"></script>
<div ng-app="test">
  <form-group classList="sample-class"></form-group>
</div>

As you can see I'm creating the form name using the scopes $id with a prefix fg_. But it doesn't work like ng-messages="fg_$id.$error" and ng-messages="fg_{{$id}}.$error" throws error.

What is the proper way to do this, or if not, how can we get around it?


P.S: I've read this question, a few similar ones and articles, but none of them answers this simple scenario

Community
  • 1
  • 1
T J
  • 42,762
  • 13
  • 83
  • 138

2 Answers2

1

Try using this['fg_' + $id].$error as parameter to ngMessages directive.

You can find working jsfiddle here.

Yevgeniy.Chernobrivets
  • 3,194
  • 2
  • 12
  • 14
0

angular.module('test', ['ngMessages'])
  .directive('formGroup', function() {
    return {
      scope: {
        classList: '='
      },
      replace: true,
      template: '<div class=\"container\" ng-class=\"classList\" ng-form=\"fg_{{$id}}\"><input type=\"text\" name=\"testInput\" ng-model=\"testValue\"  required><div ng-messages=\"this[\'fg_\' + $id].$error\"><p ng-message=\"required\">Something is wrong!<\/p><\/div><\/div>'
    }
  });
div.container {
  height: 100px;
  padding: 5px;
  border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular-messages.js"></script>
<div ng-app="test">
  <form-group classList="sample-class"></form-group>
</div>
DK3
  • 403
  • 2
  • 10