指令中的属性值始终未定义

时间:2017-03-06 19:32:41

标签: javascript angularjs

这是我的自定义指令:

angular
    .module('accountApp')
    .directive('uniqueRecord', function($q, $timeout, $http) {
        return {
            require: 'ngModel',
            link: function(scope, elm, attrs, ctrl) {

                ctrl.$asyncValidators.uniqueRecord = function(modelValue, viewValue) {

                    var value = modelValue || viewValue;

                    var attributes = scope.$eval(attrs.uniqueRecord);

                    // Lookup effect by name
                    return $http.get(attributes.url + '/' + value + '/' + ((attributes.currentRecordName == '' || attributes.currentRecordName == 'nothing') ? '_' : attributes.currentRecordName))
                                .then(function resolved() {
                                    //username exists, this means validation fails
                                    return $q.reject('exists');
                                }, function rejected() {
                                    //username does not exist, therefore this validation passes
                                    return true;
                                });
                };
            }
        }
    });

这是HTML:

<input type="text" id="name" name="name" class="form-control form-input" ng-model="effect.name"
        ng-disabled="isReadOnly" required 
        unique-record="{ url: '/api/effect', currentRecordName: {{currentEffectName == '' ? 'nothing' : currentEffectName}} }" 
        ng-uniqueRecord-err-type="duplicateRecord"/>

正如您在上面的HTML中看到的,我将currentRecordName的值传递给指令。在指令中,url的值按原样传递,但currentRecordName的值始终未定义。为什么呢?

1 个答案:

答案 0 :(得分:1)

问题来自你在躲避表达中使用小胡子。 evaled表达式已被视为角度表达式,不需要小胡子。

我建议你将你的html改为:

<input type="text" id="name" name="name" class="form-control form-input" ng-model="effect.name"
    ng-disabled="isReadOnly" required 
    unique-record="{ url: '/api/effect', currentRecordName: currentEffectName }" 
    ng-uniqueRecord-err-type="duplicateRecord"/>

并处理currentEffectName vs&#39;没有&#39;直接在指令代码中。

var attributes = scope.$eval(attrs.uniqueRecord);
if (!attributes.currentRecordName) {
  attributes.currentRecordName = 'nothing';
}