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
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".
Google is currently throwing:
Uncaught TypeError: Cannot read property 'old' of undefined
This is thrown on the second iteration of the for loop.
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