我尝试编写动态字段验证。如果选中复选框,则会在我的页面中显示新的部分。因此,在新部分中应填写一些新的输入。
我写了一个这样的自定义指令
<input .... multiValidation="Street,City,PostalCode" />
我的指令代码是
app.directive('multiValidation', function () {
return function (scope, iElement, iAttrs) {
var parts = iAttrs.myvalidate.split(',');
scope.$watch('CustomerModel.Billable', function (val) {
if (scope.CustomerModel.Billable) {
angular.forEach(parts, function (part) {
var element = angular.element('[ng-model="CustomerModel.' + part + '"]');
scope.$watch('CustomerModel.' + part, function (value) {
if (value == null || value == "") {
scope.CustomerForm.$setValidity("CustomerForm", false);
element.addClass("ng-invalid ng-invalid-required");
}
else {
element.addClass("ng-valid ng-valid-required");
var validate = true;
angular.forEach(parts, function (part) {
if (scope["CustomerModel." + part ] == "")
validate = false;
});
scope.CustomerForm.$setValidity("CustomerForm", validate);
}
});
});
} else {
if (scope.CustomerModel.LastName == "" || scope.CustomerModel.LastName == null)
scope.CustomerForm.$setValidity("CustomerForm", false);
if (scope.CustomerModel.LastName != "" || scope.CustomerModel.LastName != null)
scope.CustomerForm.$setValidity("CustomerForm", true);
}
}, true);
};});
我的问题是在以下行中,我无法在custom指令中动态访问范围变量。
scope["CustomerModel." + part ]
请指导我!!
答案 0 :(得分:0)
CustomerModel也是$ scope的变量。然后我加载了包含更多属性的CustomerModel表单数据库。
我可以像访问
一样访问CustomerModel的属性 $scope.CustomerModel.postalCode
以下方式动态访问它们是错误的
scope['CustomerModel.postalCode']
正确的方法是
scope['CustomerModel']['postalCode']
整个代码是
app.directive('myvalidate', function () {
return function (scope, iElement, iAttrs) {
var parts = iAttrs.myvalidate.split(',');
scope.$watch('CustomerModel.billable', function (val) {
if (scope.CustomerModel.billable) {
angular.forEach(parts, function (part) {
var element = angular.element('[ng-model="CustomerModel.' + part + '"]');
scope.$watch('CustomerModel.' + part, function (value) {
if (value == null || value == "") {
scope.CustomerForm.$setValidity("CustomerForm", false);
element.addClass("ng-invalid ng-invalid-required");
}
else {
element.addClass("ng-valid ng-valid-required");
var validate = true;
angular.forEach(parts, function (p) {
if (scope['CustomerModel'][p] == "" || scope['CustomerModel'][p] == "undefined" || scope['CustomerModel'][p] == null)
validate = false;
});
if (scope.CustomerModel.customerLastName == "" || scope.CustomerModel.customerLastName == null) validate = false;
scope.CustomerForm.$setValidity("CustomerForm", validate);
}
});
});
} else {
if (scope.CustomerModel.customerLastName == "" || scope.CustomerModel.customerLastName == null)
scope.CustomerForm.$setValidity("CustomerForm", false);
if (scope.CustomerModel.customerLastName != "" || scope.CustomerModel.customerLastName != null)
scope.CustomerForm.$setValidity("CustomerForm", true);
}
}, true);
};
});
和指令
<div class="panel-body" myvalidate="street,city">