2014-02-13 34 views
0

可以在指令模板(如plunker示例)中使用ui-validate嗎?在指令模板中使用ui-validate

Plunker:http://plnkr.co/edit/H6v6nVobIM3EKmAVHZHa?p=preview

template.html

<div class="form-group" ng-class="{'has-error' : !isValid()}"> 
    <label for="{{name}}" class="control-label">{{label}}</label> 
    <div class="input-group"> 
    <span class="input-group-addon">US$</span> 
    <input type="number" 
     ng-model="ngModel" 
     ng-required="isRequired" 
     ui-validate="'$value > 0'" 
     class="form-control" 
     name="{{name}}" 
     id="{{name}}" 
    /> 
    </div> 
</div> 

的script.js

.directive('currency', function() { 
    return { 
    restrict : 'E', 
    replace  : true, 
    transclude : true, 
    require  : 'ngModel', 
    scope  : { ngModel: '=' }, 
    templateUrl : 'template.html', 
    link  : function(scope, elm, attr, ctrl) { 

     scope.name = (attr.name || 'undefinedName'); 
     scope.label = (attr.label || 'undefinedLabel'); 
     scope.isRequired = (attr.required !== undefined); 

     scope.isValid = function() { 
     return ctrl.$valid; 
     }; 
    } 
    }; 
}); 

用法:

<currency ng-model="foo.value" name="value" label="Value:" required></currency> 

回答

3

通過桑德利亞

ngModel是非常強大的,但它也對周圍環境非常挑剔。由於transclude和隔離範圍,ngModel不會在表單中註冊自己。 但對於ui驗證,它足以讓ng控制器本身。

要解決基本上是從指令中只是刪除:

require : 'ngModel' 

,使:

https://groups.google.com/forum/#!topic/angular/cMgxWTM-j00

var ctrl = elm.find('input').data('$ngModelController'); 

的完整論述可以看出