how can I access ngModel from directive controller

2.6k views Asked by At
function prMySelects() {
  var ddo = {
    restrict: 'E',
    templateUrl: 'template.html',
    require: '?ngModel',
    scope: {
      ngModel: '='
    },
    controller: prMySelectsController,
    controllerAs: 'vm',
    bindToController: true
  };
  return ddo;
}

function prMySelectsController($locale) {
   ...
}

I need do some checks inside directive controller and set ngModel.$setValidity('some', false), but getting ngModel is not defined error. Injecting ngModel didn't help...

PS I know that I can access it in link, but is it possible to reach ngModel controller in directive controller?

1

There are 1 answers

1
mkalish On

This sort of functionality is best done inside the link function for a directive.

function prMySelects() {
    return {
       restrict: 'E',
       require: '?ngModel',
       link: function(scope, element, attributes, ngModel) {
          scope.theModel = ngModel;
       },
       controller: function() {
           var vm = this;
            vm.theModel.$setViewValue...
       }
    }
}

In this case, your are actually getting a hook into the ngModel controller and its not required that you actually specifiy it on the scope.