2017-03-06 36 views
0

這裏是我的自定義指令:價值指令屬性始終是不確定

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

問題來自於您在使用evaled表達式中使用鬍子。 一個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直接在指令代碼「無」。

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

Oups,對不起,我沒有看到你已經解決了它。 –

+0

好的沒問題。感謝您的幫助。我會upvote。 – Vishal

+0

我測試了你的答案,它工作正常。所以我會刪除我的答案並接受你的答案。感謝幫助。 – Vishal