简体   繁体   English

从控制器注入角度元素但不作为指令工作

[英]Injecting angular element from controller but not working as directive

My problem is that a html element needs to be replaced with a directive on event call.我的问题是 html 元素需要替换为事件调用指令。 So i am calling a function in my controller on click event and appending the angular element at the desired position, that angular element is a directive so i need to do something to make it recognizable as directive.所以我在点击事件时调用我的控制器中的一个函数并将角度元素附加到所需的位置,该角度元素是一个指令,所以我需要做一些事情以使其可识别为指令。 I have tried $compile but that doesn't work at controller level.我试过 $compile 但这在控制器级别不起作用。

My controller Code我的控制器代码

angular.element(document.body).append("<annotation></annotation> ");

My Directive code我的指令代码

app.directive("annotation", function($compile){

var linker = function(scope,element, attrs){
    element.html("Done "+attrs.content);

    if(attrs.content){

        $(element).tooltipster({
            content: $("<button class=\"btn btn-primary\">Highlight</button>"),
            animation: 'fade',
            delay: 200,
            interactive: true,
            theme: 'tooltipster-default',
            touchDevices: false,
            trigger: 'hover'
          });
    }

    $compile(element)(attrs);
}

return {
    restrict : "E",
    template: '<div class="highlightor"></div>',
    replace : true,
    link : linker,
    scope: {
        content: "="
    }
};

}); });

Update: : Something akin to this might work:更新::类似的东西可能会起作用:

.controller('myController', ['$scope', '$compile', function ($scope, $compile) {
    $scope.onClick = function () {
        angular.element(document.body).append(
                $compile("<annotation></annotation>")($scope)
        );
    };
}]);

It can be made to work the way you want by injecting $compile into the controller and then doing DOM manipulation therein.通过将$compile注入控制器然后在其中进行 DOM 操作,它可以按照您想要的方式工作。 However, it is not the correct approach and flouts one of the rules from Zen of Angular .但是,这不是正确的方法,并且违反了Zen of Angular的规则之一

Do not do DOM manipulations in the Controller.不要在控制器中进行 DOM 操作。

The Correct Way (TM), IMO, will be to have the click change a boolean flag on the $scope in the controller and then using that boolean flag to switch between the templates: IMO 的正确方法 (TM) 将是单击更改控制器中$scope上的布尔标志,然后使用该布尔标志在模板之间切换:

Template:模板:

<div ng-if="!annotationVisible" ng-click="showAnnotation()">
    Click here to see annotations.
</div>
<div ng-if="annotationVisible"><annotation></annotation></div>

Controller:控制器:

$scope.annotationVisible = false;
$scope.showAnnotation = function () { $scope.annotationVisible = true; };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM