我正在尝试使用ngMessages指令提供的验证为输入构建一些自定义指令。不过,我无法从$ scope链接多个变量来动态确定表单名称和输入名称。到目前为止,这是我的代码:
指令:
app.directive('textBox', ['$compile', function ($compile) {
return {
restrict: 'E',
scope: {
label: "@",
fieldName: "@",
bindTo: "="
},
require: "^form",
templateUrl: '/WebClient/Directives/TextBox/textBoxTemplate.html',
link: function (scope, element, attrs, ctrl) {
$scope.formName = ctrl.$name;
}
};
}]);
模板:
<div>
<label>{{label}}</label>
<input type="text" name="{{fieldName}}" ng-model="{{field}}" required />
<div ng-messages="{{formName}}.{{fieldName}}.$error">
<div ng-message="required">You left the field blank...</div>
<div ng-message="minlength">Your field is too short</div>
<div ng-message="maxlength">Your field is too long</div>
<div ng-message="email">Your field has an invalid email address</div>
</div>
</div>
用法:
<text-box bind-to="myField" field-name="myField"></text-box>
我遇到的问题与ng-messages属性值有关。当我使用花括号并且它呈现文本&#34; formName.fieldName时,似乎不起作用。$ error&#34;如果我不这样做。另一个问题与ng模型有关,适用相同的情况。
谢谢!
答案 0 :(得分:0)
您可以将链接方法中的formController
,ctrl
传递给scope.form = ctrl;
等指令范围。
然后,您可以添加<div ng-messages="form[fieldName].$error">
来访问$error
属性。
只有输入字段的名称才需要大括号。对于ng-model,您可以直接添加模型而不用curly,因为ng-model需要双向绑定才能工作。
请查看下面的演示或此jsfiddle。
angular.module('demoApp', ['ngMessages'])
.controller('mainController', MainController)
.directive('textBox', ['$compile', function ($compile) {
return {
restrict: 'E',
scope: {
label: "@",
fieldName: "@",
bindTo: "="
},
require: "^form",
templateUrl: '/WebClient/Directives/TextBox/textBoxTemplate.html',
link: function (scope, element, attrs, ctrl) {
//$scope.formName = ctrl.$name;
scope.form = ctrl;
}
};
}]);
function MainController($scope) {
$scope.myField = 'test';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular-messages.js"></script>
<div ng-app="demoApp" ng-controller="mainController">
<form name="testForm">
<text-box bind-to="model" field-name="myField"></text-box>
</form>
{{model}}
<script type="text/ng-template" id="/WebClient/Directives/TextBox/textBoxTemplate.html">
<div>
<label>{{label}}</label>
<input type="text" name="{{fieldName}}" ng-model="bindTo" required />
<div ng-messages="form[fieldName].$error">
<div ng-message="required">You left the field blank...</div>
<div ng-message="minlength">Your field is too short</div>
<div ng-message="maxlength">Your field is too long</div>
<div ng-message="email">Your field has an invalid email address</div>
</div>
</div>
</script>
</div>