When I inject $state/$stateParams into the directive they are not available inside the unique function, why?
'use strict';
angular.module('TGB').directive('uniqueSchoolclassnumberValidator', function (schoolclassCodeService) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
ngModel.$asyncValidators.unique = function (schoolclassNumer) {
var schoolyearId = 1; // Read schoolyearId from the $stateParams.id but how to inject?
return schoolclassCodeService.exists(schoolyearId, schoolclassNumber);
};
}
};
});
UPDATE
As you see in my google chrome console $stateParams or $state are undefined!
You will need a Controller
defined as part of your directive wherein $stateParams
can be injected. Something along these lines should work (untested)
(function (){
angular
.module('TGB')
.directive('uniqueSchoolclassnumberValidator', schoolclassDirective);
schoolclassDirective.$inject = ['$state', '$stateParams', '$compile','schoolclassCodeService'];
function schoolclassDirective($state, $stateParams, $compile,schoolclassCodeService) {
var directive = {
restrict: 'A',
require: 'ngModel',
controller : MyController
link: function (scope, element, attrs, listOfCtrls) {
// you will need to get the ngModelCtrl from the list of controllers as you have the require field set above
var ngModelCtrl = listOfCtrls[0]//[1];
var myCtrl = listOfCtrls[1]//[0];
ngModelCtrl.$asyncValidators.unique = function (schoolclassNumer) {
var schoolyearId = myCtrl.id;
return schoolclassCodeService.exists(schoolyearId, schoolclassNumber);
};
};
};
function MyController($state, $stateParams){
var scope = this;
scope.id= $stateParams.schoolyearId;
}
return directive;
}}
Also please go through the usage of $stateParams
from the wiki
The other way to get the 1
which if it is part of a parent state would be to define the resolve
function of the parent state and use that within the controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With