【问题标题】:Injecting angular element from controller but not working as directive从控制器注入角度元素但不按指令工作
【发布时间】:2014-03-22 09:54:56
【问题描述】:

我的问题是 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: "="
    }
};

});

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    更新::类似的方法可能有效:

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

    可以通过将$compile 注入控制器,然后在其中进行DOM 操作,使其按照您想要的方式工作。但是,这不是正确的方法,并且违反了Zen of Angular 的规则之一。

    不要在 Controller 中进行 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; };
    

    【讨论】:

    • 但我需要将此标签插入到用户定义注释的各个位置。
    • 所以我不能在 html 视图中声明这个标签,因为它是在调用 api 进行注释后知道的。
    • @user3351458 更新了答案。这会让您离解决问题更近一步吗?
    • 抱歉,没有。
    • 你能告诉我如何在我的控制器中注入编译器
    猜你喜欢
    • 2017-10-25
    • 2014-05-21
    • 2015-01-29
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 2015-04-06
    相关资源
    最近更新 更多