加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 将$state或$stateParams注入到使用angular ui路由

发布时间:2020-12-17 07:23:40 所属栏目:安全 来源:网络整理
导读:当我将$state / $stateParams注入指令时,它们在unique函数中不可用,为什么? 'use strict';angular.module('TGB').directive('uniqueSchoolclassnumberValidator',function (schoolclassCodeService) { return { restrict: 'A',require: 'ngModel',link: fun
当我将$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并在控制器内使用它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读