angularjs – 将$state或$stateParams注入到使用angular ui路由器不可能的指令中

前端之家收集整理的这篇文章主要介绍了angularjs – 将$state或$stateParams注入到使用angular ui路由器不可能的指令中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我将$state / $stateParams注入指令时,它们在unique函数中不可用,为什么?
'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

正如您在我的谷歌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',controller : MyController
      link: function (scope,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的使用情况

如果它是父状态的一部分,获得1which的另一种方法是定义解决方function of the parent state并在控制器内使用它.

猜你在找的Angularjs相关文章