[英]AngularJS use Directive from controller
i need to use directive from controller in angular 1.6.*.我需要在 angular 1.6.* 中使用来自控制器的指令。
I explain better with code.我用代码解释得更好。
Controller控制器
$scope.directive = [
"<span my-directive></span>",
"<span my-directive2></span>",
"<span my-directive3></span>"
]
HTML HTML
<div>{{directive}}</div>
My solution is:我的解决办法是:
Controller控制器
directive.forEach(function (item) {
$compile(item)($scope).appendTo('.navbar');
})
HTML HTML
<div class="navbar"></div>
But my solution is DOM dependent, is a bad solution.但我的解决方案依赖于 DOM,是一个糟糕的解决方案。
I need a smart solution.我需要一个聪明的解决方案。
Any ideas?有任何想法吗?
Thanks!谢谢!
You could create your own directive which will do this binding for you similarly to ng-bind
and ng-bind-html
.您可以创建自己的指令,该指令将为您执行此绑定,类似于
ng-bind
和ng-bind-html
。
Please consider the following example:请考虑以下示例:
Directive指示
function MyBindCompileDirective($compile) {
return {
restrict: 'A',
link(scope, elem, attrs) {
attrs.$observe('myBindCompile', () => elem.html($compile(scope.myBindCompile)(scope).html()))
}
};
}
angular
.module('app')
.directive('myBindCompile', MyBindCompileDirective);
Usage in HTML在 HTML 中的使用
<div ng-repeat="item in directives" my-bind-compile="item"></div>
I would iterate in a ngRepeat and put the directive directly, changing only what is needed.我会在 ngRepeat 中迭代并直接放置指令,只更改需要的内容。 collection is defined in the controller
集合在控制器中定义
<div ng-repeat="model in collection">
<span my-directive variable="model"></span>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.