1

I'm creating a custom directive to show form errors (using ng-messages) in a generic way. The directive will be invoked via:

<show-errors form="login_form" field="email"></show-errors>
...
<show-errors form="login_form" field="password"></show-errors>

the directive declaration:

function showGenericErrors() {
  return {
    restrict: 'E',
    templateUrl: 'views/error.dir.tmpl.html',
    replace: true,
    scope: {
      form: '@',
      field: '@'
    },
    transclude: true,
    link: function (scope, element, attrs, ctrl, transclude) {
      scope.theForm = scope.$parent[attrs.form];
      transclude(scope, function (clone, scope) {
        element.append(clone);
      });
    }
  };
}

And it's template:

<div>
  <!-- Here I can access form property via bracket notation -->
  <!-- {{theForm[field].$blurred }} -->

  <!-- But here I cannot use the same notation inside ng-if -->
  <div class="error" ng-if="theForm[field].$blurred" ng-messages="theForm[field].$error" ng-messages-include="views/errors.html">
  </div>
</div>

The template does not work!

Since, I would be using this directive on multiple forms & fields, how do I validate the conditions in the directive template. Or is there a better way to handle this?

anand
  • 695
  • 9
  • 21
  • i think you need to use it like `ngif="{{theForm[field].$blurred}}"` http://stackoverflow.com/questions/14050195/what-is-the-difference-between-and-in-directive-scope?lq=1 – batmaniac7 Apr 14 '15 at 17:22
  • 1
    You don't need to transclude, because you would not need to have access to outer scope. – André Werlang Apr 14 '15 at 23:17

1 Answers1

3

Solved!

the new directive:

function showErrors() {
  return {
    restrict: 'E',
    templateUrl: 'views/error.dir.tmpl.html',
    replace: true,
    scope: {
      form: '@',
      field: '@'
    },
    link: function(scope, element, attrs, ctrl) {
      scope.theForm = scope.$parent[attrs.form];
      scope.formField = scope.theForm[attrs.field];
    }
  };
}

the new template:

<div>
  <div class="error" ng-if="formField.$blurred" ng-messages="formField.$error" ng-messages-include="views/errors.html">
  </div>
</div>
anand
  • 695
  • 9
  • 21