本文介绍了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在指令中应用类
发布评论