我无法找到满足部分或全部这些需求的答案。这是我想出的。
可能有更好的方法,请分享您的想法。
我使用Angularjs 1.3.0-beta.8
我与多嵌套指令,所有包含输入(S)形式,选择(一个或多个),等... 这些元件都包含在ng-repeats和动态字符串值。
这是如何使用的指令:
<form name="myFormName">
<nested directives of many levels>
ex: <input ng-repeat=(index, variable) in variables" type="text"
my-name="{{ variable.name + '/' + 'myFormName' }}"
ng-model="variable.name" required />
ex: <select ng-model="variable.name" ng-options="label in label in {{ variable.options }}"
my-name="{{ variable.name + '/' + 'myFormName' }}"
</select>
</form>
注意:你可以,如果你需要或许序列化的输入表中添加和指数的字符串连接;这就是我所做的。但是,动态名称输入意味着您可能不知道表单输入的名称,那么您将如何调用$ scope.formName。??????。您可以迭代$ scope.formName对象以获得匹配特定值的键。这意味着字符串连接这样的:
my-name="{{ dynamicString + hello + '/' + 'myFormName' }}"
然后在$ scope.myFormName则可以通过将只是遍历对象和收集,包括“你好”的任何键找到任何形式的输入名称。
app.directive('myName', function(){
var myNameError = "myName directive error: "
return {
restrict:'A', // Declares an Attributes Directive.
require: 'ngModel', // ngModelController.
link: function(scope, elem, attrs, ngModel){
if(!ngModel){ return } // no ngModel exists for this element
// check myName input for proper formatting ex. something/something
checkInputFormat(attrs);
var inputName = attrs.myName.match('^\\w+').pop(); // match upto '/'
assignInputNameToInputModel(inputName, ngModel);
var formName = attrs.myName.match('\\w+$').pop(); // match after '/'
findForm(formName, ngModel, scope);
} // end link
} // end return
function checkInputFormat(attrs){
if(!/\w\/\w/.test(attrs.rsName)){
throw myNameError + "Formatting should be \"inputName/formName\" but is " + attrs.rsName
}
}
function assignInputNameToInputModel(inputName, ngModel){
ngModel.$name = inputName
}
function addInputNameToForm(formName, ngModel, scope){
scope[formName][ngModel.$name] = ngModel; return
}
function findForm(formName, ngModel, scope){
if(!scope){ // ran out of scope before finding scope[formName]
throw myNameError + "<Form> element named " + formName + " could not be found."
}
if(formName in scope){ // found scope[formName]
addInputNameToForm(formName, ngModel, scope)
return
}
findForm(formName, ngModel, scope.$parent) // recursively search through $parent scopes
}
});
这应该处理很多情况下,你只是不知道窗体将在哪里。或者您可能嵌套了表单,但出于某种原因,您希望将此输入名称附加到两个表单中?那么,只需传入您想要附加输入名称的表单名称即可。
我想要的是一种将动态值分配给我永远不会知道的输入的方法,然后调用$ scope.myFormName。$ valid。
这可能是一个矫枉过正的问题,1.3+中存在更好的解决方案。我无法在我的时间找到它。这现在适合我。
祝你好运!希望这可以帮助别人!
http://stackoverflow.com/questions/21455695/angularjs-dynamic-form-field-validation/21457121#21457121 – 2015-06-06 04:29:09