当我将$ state/$ stateParams注入(inject)指令时,它们在唯一函数中不可用,为什么?

'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);
            };
        }
    };
});

更新

angularjs - 使用angular ui路由器无法将$ state或$ stateParams注入(inject)指令-LMLPHP

正如您在我的Google Chrome浏览器控制台中看到的那样,$ stateParams或$ state是未定义的!

最佳答案

您将需要将Controller定义为指令的一部分,可以在其中插入$stateParams。遵循这些思路的东西应该起作用(未经测试)

(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;
}}

还请仔细阅读wiki$stateParams的用法

获取1的另一种方法(如果它是父状态的一部分)将是定义resolve function of the parent state并在 Controller 中使用它。

10-07 23:20