使用angularjs和材质,我希望能够拥有一个只读文本框,该文本框显示用户查找的选定对象的名称(通过模式弹出窗口),但该文本框验证应按要求显示,如果未填充单独的id属性。这是一个示例plnkr。
我本来以为我可以简单地通过添加一个具有ng-model,name和required属性的隐藏字段来做到这一点,它将为具有所需验证器的字段创建关联的form属性(并这样做),并且我将能够在只读文本框中显示验证器,如下所示:
<form name="myCtrl.myForm" novalidate>
<input type="hidden" ng-model="myCtrl.id" name="id" required />
<div layout="row">
<md-input-container flex="50">
<label>Selected Object</label>
<input ng-model="myCtrl.selectedObject.selectedText" readonly />
<div ng-messages="myCtrl.myForm.id.$error">
<div ng-message="required">Please select an object.</div>
</div>
</md-input-container>
<div>
<md-button class="md-icon-button md-primary" ng-click="myCtrl.select($event)">
<md-tooltip md-direction="top">
Select Object
</md-tooltip>
<md-icon>search</md-icon>
</md-button>
</div>
</div>
<div>
<md-button class="md-raised md-primary" type="submit">Submit</md-button>
</div>
</form>
JS:
vm.select = function(evt) {
// Set the selected Object
vm.selectedObject = { selectedText: "Object id 1 selected", id: 1 };
// Set the associated ID
vm.id = 1;
};
但是,<div ng-message="required">Please select an object.</div>
永远不会在提交表单和触发验证时显示。知道我怎么能做到吗?
答案 0 :(得分:0)
当我输入这个问题时,我有一个主意-也许我应该创建一个自定义验证器,以便将其应用于引用了单独属性的此输入。这似乎可以满足我的需求。这是plnkr,这是指令:
add_action( 'template_redirect', 'redirect_externally' );
function redirect_externally(){
$redirect = get_post_meta( get_the_ID(), 'redirect_to_here', true );
if( $redirect ){
wp_redirect( $redirect );
}
}
这是更新的HTML:
angular.module('MyApp', ['ngMessages', 'ngMaterial'])
.directive('requiredOther', RequiredOther);
function RequiredOther() {
return {
require: "ngModel",
scope: {
requiredOtherValue: "=requiredOther"
},
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.requiredOther = function(modelValue) {
return scope.requiredOtherValue !== undefined && scope.requiredOtherValue !== null && scope.requiredOtherValue !== '';
};
scope.$watch("requiredOtherValue", function() {
ngModel.$validate();
});
}
};
}
<form name="myCtrl.myForm" novalidate>
<input type="hidden" ng-model="myCtrl.id" />
<div layout="row">
<md-input-container flex="50">
<label>Selected Object</label>
<input name="id" ng-model="myCtrl.selectedObject.selectedText" readonly required-other="myCtrl.id" />
<div ng-messages="myCtrl.myForm.id.$error">
<div ng-message="requiredOther">Please select an object.</div>
</div>
</md-input-container>
<div>
<md-button class="md-icon-button md-primary" ng-click="myCtrl.select($event)">
<md-tooltip md-direction="top">
Select Object
</md-tooltip>
<md-icon>search</md-icon>
</md-button>
</div>
</div>
<div>
<md-button class="md-raised md-primary" type="submit">Submit</md-button>
</div>
</form>
指令引用id属性并监视更改并在更改时触发验证:
我想我也不再需要隐藏的输入字段。