[英]Creating multiple levels of json from loop
I'm writing a directive in angular to help validate fields. 我正在用角度编写指令,以帮助验证字段。 It is working up to the point of storing the result of the validation.
直到存储验证结果为止。
I want to store it in an object like error.password.old
我想将其存储在像
error.password.old
这样的对象中
the code to do this looks like this: 执行此操作的代码如下所示:
if(!(typeof iAttrs.ngModel == "undefined"))
{
var model = iAttrs.ngModel.split('.');
var length = model.length;
var target = scope.error;
if(typeof validation[iAttrs.validate] == "function")
{
for(var index = 0; index < length; index++)
{
target = target[model[index]];
}
target = validation[iAttrs.validate]();
scope.$apply();
}
else throw("function " + iAttrs.validate + " does not exist.");
}
iAttrs.ngModel is holds "password.old". iAttrs.ngModel保存为“ password.old”。
Google is currently throwing: Google当前抛出:
Uncaught TypeError: Cannot read property 'old' of undefined
未捕获的TypeError:无法读取未定义的属性“ old”
This is thrown on the second iteration of the for loop. 这是在for循环的第二次迭代中引发的。
I understand that it is undefined but i need to find a way to define it on the fly without the normal {} notation. 我了解它是未定义的,但是我需要找到一种无需常规{}表示法即可动态定义它的方法。
I am using following code to do that. 我正在使用以下代码来做到这一点。
function createObj( str ) {
var d = str.split("."), j, o = scope.error;
for (j = 0; j < d.length; j = j + 1) {
o[d[j]] = o[d[j]] || {};
o = o[d[j]];
}
return o;
}
createObj(iAttrs.ngModel);
You can use the $parse
service: http://docs.angularjs.org/api/ng.$parse 您可以使用
$parse
服务: http : //docs.angularjs.org/api/ng.$parse
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.