当我将$ 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);
};
}
};
});
更新
正如您在我的谷歌Chrome控制台中看到的那样$ stateParams或$ state未定义!
答案 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并在控制器中使用它。