2017-10-18 44 views
0

在试图调试与角度的要求指令的问题,我有重复的功能自己:

.directive("myRequired", function(){ 
    return { 
    restrict: 'A', 
    require: 'ngModel', 
    link: function(scope, elm, attr, ctrl) { 
     if (!ctrl) return; 
     attr.myRequired = true; // force truthy in case we are on non input element 

     ctrl.$validators.myRequired = function(modelValue, viewValue) { 
     return !attr.myRequired || !ctrl.$isEmpty(viewValue); 
     }; 

     attr.$observe('myRequired', function() { 
     ctrl.$validate(); 
     }); 
    } 
    }; 
}) 

我使用的md-select输入与该指令下列选项:

$scope.options = [ 
     { name: "option1", id: 1 }, 
     { name: "option2", id: 2 }, 
     { name: "option3", id: 3 } 
    ]; 

当我的模型对我的选择预先填充值,就像这样:

$scope.myModel = {mySelect: 1};

然后myRequired指令失败,因为ctrl.$isEmpty()返回viewValue(即,或者true

它为什么这样做?

如何让它返回一个布尔值?

+0

这是奇怪的,因为'$ isEmpty' [总是返回一个布尔](https://github.com/angular/angular.js/blob/c8d349870812284a82896087c05c2d19c8f5cdfd/src/ng/directive/ngModel.js#L363)。你可以发布一个闯入者来重现问题吗? –

+0

如果您的选择有预先填充的值,您期望什么行为?在我看来,验证应该成功,因为存在价值。验证不成功吗? –

+0

正确,验证失败 – kat

回答