Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

enter image description here

As you see in my google chrome console $stateParams or $state are undefined!

like image 703
HelloWorld Avatar asked Jan 24 '16 21:01

HelloWorld


1 Answers

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 1which 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.

like image 99
Ahmad Avatar answered Oct 24 '22 07:10

Ahmad