如何在 AngularJS 中的输入组件上使用 ng-model



这是我的html文件代码

<form name="myForm" ng-controller="ExampleController" novalidate="">
<email classname="form-control" name="Email" type="email" modelname="email_id" 
placeholder="Email Address" formref="myForm" ></email>
<button ng-click="Click()">click</button>

我希望当我单击按钮时,它给了我电子邮件的值,使用了ng-model(email_id(的值-

$scope.Click = function(){
console.log($scope.email_id);
};

这是我的组件代码

angular.module('textInputExample', []).component("email", {
template:
'<input type="{{$ctrl.type}}" class="{{$ctrl.classname}}" 
placeHolder="{{$ctrl.placeholder}}" name="{{$ctrl.name}}" ng- 
model="$ctrl.modelname" required>' +
'<div ng-messages="$ctrl.formref[$ctrl.name].$error" ng- 
show="$ctrl.formref[$ctrl.name].$touched">' +
'<p ng-message="required">Providing a {{$ctrl.placeholder}} is 
mandatory.</p>' +
'<p ng-message="email">{{$ctrl.placeholder}} is invaild</p></div>',
bindings: {
formref: '<',
name: '@',
placeholder: '@',
classname: '@',
type: '@',
modelname:'='
}

在上面的组件代码中,我使用该模型名称值分配给 ng-model 属性,然后我想在控制器中使用该值来访问输入字段值,但我没有将 ng-model 设置为我正在分配的值(email_id(,而且我无法访问输入字段的值。 请帮助我该怎么办。 如果需要任何信息重新分级此问题以解决问题,请通知我。

我找到了我的解决方案。 如果有人遇到同样的问题,这是我的解决方案 -

将此代码写入您的 JS 文件中

component("email", {
bindings: { ngModel: '<' },
require: { ngModelCtrl: 'ngModel' },
template:
`<input type="{{$ctrl.type}}" class="{{$ctrl.classname}}" placeHolder="{{$ctrl.placeholder}}" name="{{$ctrl.name}}" ng-model='$ctrl.ngModel'
ng-change="$ctrl.ngModelChange()" required>
<div ng-messages="$ctrl.formref[$ctrl.name].$error" ng-show="$ctrl.formref[$ctrl.name].$touched">
<p ng-message="required">Providing a {{$ctrl.placeholder}} is mandatory.</p>
<p ng-message="email">{{$ctrl.placeholder}} is invaild</p></div>`,
bindings: {
formref: '<',
name: '@',
placeholder: '@',
classname: '@',
type: '@',
modelname:'='
},
controller: function() {
this.ngModelChange = () => {
this.ngModelCtrl.$setViewValue(this.ngModel);
};
}

这是 html 文件代码

<email classname="form-control" name="Email" type="email" ng-model="email_id" 
placeholder="Email Address" formref="myForm" ></email>

谢谢你对大家的帮助

<input type="{{$ctrl.type}}" class="{{$ctrl.classname}}" placeHolder="{{$ctrl.placeholder}}" name="{{$ctrl.name}}" ng- model="$ctrl.modelname" required>

尝试绑定 ng 模型,然后您可以从 HTML 文件中获取值。尝试使用以下代码片段更改代码。

<input type="{{$ctrl.type}}" class="{{$ctrl.classname}}" placeHolder="{{$ctrl.placeholder}}" name="{{$ctrl.name}}" [(ngModel)]="$ctrl.modelname" required>

最新更新