簡體   English   中英

從控制器注入角度元素但不作為指令工作

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

我的問題是 html 元素需要替換為事件調用指令。 所以我在點擊事件時調用我的控制器中的一個函數並將角度元素附加到所需的位置,該角度元素是一個指令,所以我需要做一些事情以使其可識別為指令。 我試過 $compile 但這在控制器級別不起作用。

我的控制器代碼

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

我的指令代碼

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: "="
    }
};

});

更新::類似的東西可能會起作用:

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

通過將$compile注入控制器然后在其中進行 DOM 操作,它可以按照您想要的方式工作。 但是,這不是正確的方法,並且違反了Zen of Angular的規則之一

不要在控制器中進行 DOM 操作。

IMO 的正確方法 (TM) 將是單擊更改控制器中$scope上的布爾標志,然后使用該布爾標志在模板之間切換:

模板:

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

控制器:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM