AngularJS的自定义指令没有加载

AngularJS custom directive doesn't load

本文关键字:加载 指令 自定义 AngularJS      更新时间:2023-09-26

我使用的是angular 1.4.x。

我正在制作一个自定义指令,检查字段在服务器上是否唯一(该字段称为"jmbg")。我有以下代码:

(function() {
angular
    .module('app')
    .directive('uniqueJmbg', uniqueJmbg);
uniqueJmbg.$inject = ['$q', '$http'];
function uniqueJmbg($q, $http) {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModelCtrl) {
        ngModelCtrl.$asyncValidators.uniqueJmbg = function(modelValue, viewValue) {
            var value = modelValue || viewValue;
            return $http.get('/server/users/' + value)
                .then(function resolved() {
                    return $q.reject('exists');
                }, function rejected() {
                    return true;
             });
        };
    }
}
})();

我在HTML中以以下方式使用指令:

<input class="form-control" type="text" id="jmbg" name="jmbg" ng-model="rad.radnik.jmbg" ng-model-options="{ updateOn: 'default blur', debounce: {'default':400, 'blur':0 } }" unique-jmbg/>

如果它很重要,我将使用我的控制器和controllerAs语法。现在发生的情况是,包含我的uniqueJmbg定义的文件永远不会加载(我无法在浏览器调试器中看到它)。如果我把我的代码移动到一个组件,它加载应用程序停止工作(在控制台没有错误),所以我没有办法调试这个。

你知道是什么错了吗?我甚至不能在浏览器中访问代码?

添加依赖项到模块

angular
    .module('app', [])
    .directive(...

您需要从模块返回一个对象,因此更正将是:

function uniqueJmbg($q, $http) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elem, attrs, ngModelCtrl) {
            ...
        }
    };
}