我正在尝试为电子邮件输入创建指令。除了验证电子邮件地址格式外,一切似乎都没问题。当我输出到控制台时,ngModel似乎也没有更新。当我用ng-controller
进行检查时,模型值确实会更新,但不会在控制器内。
指令模板的代码:
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="email" name="{{name}}" id="reg-{{name}}" ng-model="model" ng-blur="setBlur()" />
<label class="mdl-textfield__label" ng-class="{'ba-textfield__label-error':showErrorPanel()}" for="reg-{{name}}">{{label}}</label>
<div ng-show="showErrorPanel()">
<span class="ba-textfield__error" ng-show="errorRequired()">{{requiredMessage}}</span>
<span class="ba-textfield__error" ng-show="errorEmail()">{{formatMessage}}</span>
</div>
</div>
电子邮件字段指令的代码:
.directive("emailInput", [function () {
return {
restrict: "E",
replace: true,
templateUrl: "email-field.html",
require: 'ngModel',
scope: {
model: '=ngModel',
name: '@name',
label: '@label',
required: '@required',
requiredMessage: '@requiredMessage',
formatMessage: '@formatMessage'
},
link: function (scope, element, attrs, ngModel) {
//set default values
if (scope.requiredMessage) { scope.requiredMessage = 'Required'; }
if (scope.formatMessage) { scope.formatMessage = 'Not valid'; }
//get input element
element.children()[0].required = scope.required.toLowerCase() == "true";
//register element with MDL
componentHandler.upgradeElement(element[0]);
scope.showErrorPanel = function () {
return ngModel.$submitted || ngModel.$touched;
};
scope.errorRequired = function () {
return ngModel.$error.required;
};
scope.errorEmail = function () {
return ngModel.$error.email;
};
scope.setBlur = function () {
ngModel.$setTouched();
};
}
}
}])