我没有解决这个问题。我尝试添加验证(如果表单提交停用,如果无效),数组是否包含项目。我尝试使用自定义指令但它在模型更新时永远不会被调用:( 因为角度内容在一个播放应用程序模板中呈现,并且表单没有在我的范围内定义,所以我不能做一些简单的表单失效。
我试图实现的是使表单无效,直到某个类别被添加到$ scope.app.categories,从而停用了提交按钮,这也不在我的范围内。
这里是代码(角度版本1.2.23):
<input type="text" ng-model="app.categories" name="size" custom />
<input id="tagsinput" type="text" ng-model="new.category" on-keyup="disabled" keys="[13]"/>
<a class="btn" ng-click="addCategory()">Add</a>
// loading of app happens above this is the contoller function
$scope.addCategory = function () {
$scope.app.categories.push({name: $scope.new.category});
$scope.new.category = "";
}
app.directive('custom', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$formatters.unshift(function(val1, val2, val3, val4) {
// not even gets called would like to validate app.categories here :(
console.log(true);
});
}
};
});
答案 0 :(得分:0)
您正在使用$formatters
,但要进行验证,您应该使用$validators
。而不是以ctrl.$formatters
开头的行,请尝试以下操作:
ctrl.$validators.yourValidatorName = function(modelValue, viewValue) {
console.log("Validator is called.");
return true; // This means validation passed.
};
您可以在documentation中找到。另外,不要忘记将指令添加到HTML元素中,因此在您的情况下<input ... custom>
。要在验证失败时禁用提交按钮,请使用<input type="submit" data-ng-disabled="formName.$invalid">
。