如何在带有$ watch的AngularJS链接函数中使用$ compile

时间:2016-11-15 22:04:23

标签: angularjs angularjs-directive angular-ui

使用AngularJS和Angular-UI工具提示(uib-tooltip)设置工具提示系统,允许用户打开工具提示&关闭。我还希望将文本保存在中央位置以便于编辑。然而,我遇到了麻烦,复制了uib-tooltip指令的工具提示启用部分,该部分切换了开/关部分。

标准方法。

<ul id="realmContainer" uib-tooltip="Even more stuffs" tooltip-placement="bottom" tooltip-enable="userService.data.current.preferences.activeTooltips">

...

我的HTML

<ul id="realmContainer" tip>

“提示”指令

(function () {
    'use strict';

    angular
        .module('app.directives')
        .directive('tip', ['$rootScope', 'userService', '$compile', Tooltip]);

    /* @ngInject */
    function Tooltip($rootScope, userService, $compile) {

        return {
            restrict: 'A',
            priority: 10000,
            terminal: true,
            link: link
        };

        function link(scope, element, attrs) {
            // lookup and assign the tooltip by ID
            attrs.$set('uib-tooltip', dictionary[element[0].id]);
            attrs.$set('tooltip-placement', attrs['tip-position'] || 'bottom');
            // Remove the 'tip' attribute so we don't get stuck in a loop
            attrs.$set('tip', null);
            // compile the new HTML.  This works so far
            $compile(element)(scope);

             //I just can't get this to recompile the html when the value changes
            scope.userService = userService;
            scope.$watch('userService.data.current.preferences.activeTooltips', function(newValue, oldValue){
                var isVisible = newValue === undefined ? true : newValue;
                // This sets true/false in the DOM
                attrs.$set('tooltip-enable', isVisible);
                // Mouseover event still triggers even after removing
                // tooltip-enable.  What gives?
                $compile(element)(scope);
            })
        }
    }

    var dictionary = {
        realmContainer: 'Even more stuffs'
    }
})();

似乎工具提示始终显示在鼠标悬停上。 $ watch会获取新值,但$ compile似乎不会从DOM中删除鼠标悬停触发器。

任何帮助都将不胜感激。

0 个答案:

没有答案