当我将$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.沿着这些方向的东西应该工作(未经测试)
原文链接:https://www.f2er.com/angularjs/141842.html(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并在控制器内使用它.