在angularjs模板中设置变量

时间:2014-06-13 08:53:37

标签: javascript angularjs angular-ui-bootstrap

我正在使用angular ui-bootstrap popover,我创建了一个新指令,以便将其传递给自定义模板。我在设置该模板中的变量时遇到问题,我无法弄清楚模板的呈现范围。有没有办法在指令中设置模板变量?或以某种方式从父控制器访问变量? 这是我的代码:

指令

app.directive('hoverPopover', function ($compile, $templateCache, $timeout, $rootScope) {
var getTemplate = function (contentType) {
    //template = $templateCache.get('popoverTemplate.html');
    return $templateCache.get('popoverTemplate.html');
};
return {
    restrict: 'A',
    link: function (scope, element, attrs) {
        scope.title = "something here";
        var content = getTemplate();
        $rootScope.insidePopover = false;
        $(element).popover({
            content: content,
            placement: 'top',
            html: true
        });
        $(element).bind('mouseenter', function (e) {
            $timeout(function () {
                if (!$rootScope.insidePopover) {
                    $(element).popover('show');
                    scope.attachEvents(element);
                }
            }, 200);
        });
        $(element).bind('mouseleave', function (e) {
            $timeout(function () {
                if (!$rootScope.insidePopover)
                    $(element).popover('hide');
            }, 400);
        });
    },
    controller: function ($scope, $element) {
        $scope.title = "something here";
        $scope.attachEvents = function (element) {
            $('.popover').on('mouseenter', function () {
                $rootScope.insidePopover = true;
            });
            $('.popover').on('mouseleave', function () {
                $rootScope.insidePopover = false;
                $(element).popover('hide');
            });
        }
    }
};
});

我的index.cshtml文件中的模板

<script type="text/ng-template" id="popoverTemplate.html">
        <div id="angularTemplate">
            This is the content of the template
            <p>Added a paragraph here</p>
            {{title}}<br />
            <button>Button</button>
        </div>
    </script>

请不要问小提琴,因为我似乎无法让一个人工作,我的指示不起作用。但是,如果您仍想在这里看到完整的图片,那就是http://jsfiddle.net/y7az9/5/

0 个答案:

没有答案
相关问题