Angular在指令中应用类

编程入门 行业动态 更新时间:2024-10-26 13:30:04
本文介绍了Angular在指令中应用类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个angular指令,它将生成bootstrap form-group,查找$ scope.errors以获取指令的ng-model值以显示错误。示例如下:我的html代码:

I have a angular directive which will produce bootstrap form-group, looks for $scope.errors for value of ng-model of the directive to show errors.. Example below: My html code:

<input type="text" b-input ng-model="datapany.name" label="Company Name" class="form-control"/>

和我的指令代码:

app.directive('bInput', function ($compile) { return { restrict: 'EA', replace: true, link: function (scope, element, attrs) { var div = $('<div>', { 'class': 'form-group', 'ng-class': " 'has-error' : errors." + attrs.ngModel + " != null " }); $compile(div)(scope); element.wrap(div); if (attrs.label != undefined) { element.before('<label for="' + attrs.name + '" class="control-label">' + attrs.label + '</label>'); element.removeAttr('label'); } } }; });

您能否解释一下我如何达到预期效果?

Can you please explain me how do i achieve the desired result?

推荐答案

修改指令的编译fn中的元素,因为DOM是普通的。然后在链接函数中重新编译该元素,该函数从编译函数返回。

Modify element inside the compile fn of the directive because at DOM is plain. and then recompile that element inside the link function which is return from compile function.

代码

app.directive('bInput', function($compile) { return { restrict: 'EA', replace: true, compile: function(element, attrs) { var div = $('<div>', { 'class': 'form-control', 'ng-class': " 'has-error' : errors." + attrs.ngModel + " != null " }); element.wrap(div); if (attrs.label != undefined) { element.before('<label for="' + attrs.name + '" class="control-label">' + attrs.label + '</label>'); element.removeAttr('label'); } element.removeAttr('b-input'); return function(scope, element, attrs) { var linkFn = $compile(element); linkFn(scope) } }; });

查看类似的 SO回答

Look at similar SO answer here

更多推荐

Angular在指令中应用类

本文发布于:2023-11-13 12:00:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584302.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指令   Angular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!