![](/img/trans.png)
[英]How bracket notation in javascript access the property of an object?
[英]In angular, how to access object property via bracket notation inside templates?
我正在创建一个自定义指令,以通用方式显示表单错误(使用ng-messages)。 该指令将通过以下方式调用:
<show-errors form="login_form" field="email"></show-errors>
...
<show-errors form="login_form" field="password"></show-errors>
指令声明:
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); }); } }; }
它是模板:
<div> <!-- Here I can access form property via bracket notation --> <!-- {{theForm[field].$blurred }} --> <!-- But here I cannot use the 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>
模板不起作用!
因为,我将在多个表单和字段上使用此指令,如何验证指令模板中的条件。 或者有更好的方法来处理这个问题吗?
解决了!
新指令:
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]; } }; }
新模板:
<div> <div class="error" ng-if="formField.$blurred" ng-messages="formField.$error" ng-messages-include="views/errors.html"> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.