javascript - In angular, how to access object property via bracket notation inside templates? -
i'm creating custom directive show form errors (using ng-messages) in generic way. directive invoked via:
<show-errors form="login_form" field="email"></show-errors> ... <show-errors form="login_form" field="password"></show-errors>
the directive declaration:
function showgenericerrors() { return { restrict: 'e', templateurl: 'views/error.dir.tmpl.html', replace: true, scope: { form: '@', field: '@' }, transclude: true, link: function (scope, element, attrs, ctrl, transclude) { scope.theform = scope.$parent[attrs.form]; transclude(scope, function (clone, scope) { element.append(clone); }); } }; }
and it's template:
<div> <!-- here can access form property via bracket notation --> <!-- {{theform[field].$blurred }} --> <!-- here cannot use same notation inside ng-if --> <div class="error" ng-if="theform[field].$blurred" ng-messages="theform[field].$error" ng-messages-include="views/errors.html"> </div> </div>
the template not work!
since, using directive on multiple forms & fields, how validate conditions in directive template. or there better way handle this?
solved!
the new directive:
function showerrors() { return { restrict: 'e', templateurl: 'views/error.dir.tmpl.html', replace: true, scope: { form: '@', field: '@' }, link: function(scope, element, attrs, ctrl) { scope.theform = scope.$parent[attrs.form]; scope.formfield = scope.theform[attrs.field]; } }; }
the new template:
<div> <div class="error" ng-if="formfield.$blurred" ng-messages="formfield.$error" ng-messages-include="views/errors.html"> </div> </div>
Comments
Post a Comment