VJAI
VJAI

Reputation: 32758

Applying validation in angularjs directives

I'm building a set of reusable components in AngularJS 1.5.x version. Each directive accepts a model like below.

<app-grid ng-model="scope.gridModel" />

The gridModel is a simple class looks like below,

function GridModel(cols) {
   this.cols = cols;
}

Is there any way I can check in the directive that the passed model is of type GridModel ?

Upvotes: 2

Views: 46

Answers (2)

Forcent Vintier
Forcent Vintier

Reputation: 159

It is possible. First, I suggest you create a service to access the GridModel object, so that you can access the object from the controller and from the directive.

myApp.service('GridService', function() {
    this.GridModel = function(cols) {
        this.cols = cols;
    };
});

Then, in your directive, you can check if the model is of type GridModel using InstanceOf.

var GridModel = GridService.GridModel;
$scope.isGridModel = ($scope.model instanceof GridModel);

I built an example with a directive that will show true if its model is of type GridModel, otherwise false. See this JSFiddle for the example.

Upvotes: 0

MarcoS
MarcoS

Reputation: 17711

I would try something like this, in my directive link function:

...
link: function (scope, element, attrs, ngModel) {
  if (ngModel instanceof GridModel) {
    // right class
  } else {
    // wrong class
  }
},
...

UPDATE: This will check the ngModel instance type instantly.
If you want to check the type in the event it changes, you should set up a $watch...
Something like this:

scope.$watch('ngModel', function(newValue, oldValue) {
  if (newValue instanceof GridModel) {
    // right class
  } else {
    // wrong class
  }
});

Upvotes: 1

Related Questions