angularjs - Inject $state or $stateParams into directive not possible with angular ui router -


when inject $state/$stateparams directive not available inside 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 $stateparams.id how inject?                 return schoolclasscodeservice.exists(schoolyearid, schoolclassnumber);             };         }     }; }); 

update

enter image description here

as see in google chrome console $stateparams or $state undefined!

you need controller defined part of directive wherein $stateparams can injected. 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) {          // need ngmodelctrl list of controllers have 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 usage of $stateparams wiki

the other way 1which if part of parent state define resolve function of parent state , use within controller.


Comments