It is not possible to inject $ state or $ stateParams into a directive using angular ui router

When I insert $ state / $ stateParams into a directive, they are not available inside a 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

enter image description here

As you can see on my Google Chrome console $ stateParams or $ state undefined!

+7
angularjs angular-ui-router
source share
1 answer

You will need a Controller defined as part of your directive in which $stateParams can be entered. Something in this direction should work (unverified)

 (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 use $stateParams from the wiki

Another way to get 1 , which, if it is part of the parent state, would be to define the resolve function of the parent state and use this in the controller.

+7
source share

All Articles