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

时间:2016-01-24 21:07:59

标签: angularjs angular-ui-router

当我将$ 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);
            };
        }
    };
});

更新

enter image description here

正如您在我的谷歌Chrome控制台中看到的那样$ stateParams或$ state未定义!

1 个答案:

答案 0 :(得分:8)

您需要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并在控制器中使用它。