2

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 ?

2 Answers 2

1

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
  }
});
Sign up to request clarification or add additional context in comments.

4 Comments

This will work only for the first time rgt? What happens if the model changes later. Let's say somewhere sometime the model is set to a different type.
That's cool. I'm little new to angular and so one more question. The scope.$watch will do a deep watch rgt? If so the case how I can make the watch more flat here?
You can control the depth of a $watch with the 3rd parameter:
scope.$watch('ngModel', function (newVal, oldVal) { /*...*/ }, true); is deep, while scope.$watch('ngModel', function (newVal, oldVal) { /*...*/ }, false); is not...
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.