繁体   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