Angular 表带。弹出框编程使用

Angular Strap. Popover programmatic use

我正在尝试以编程方式创建弹出框,但遇到了以下问题。我无法访问弹出框模板内的父范围。预期结果是:

Hello my name is Roman

但我明白了

Hello my name is undefined

这里是plunker

如果我使用 bs-popover 作为任何元素的属性,那么我会得到预期的结果。

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <title>Popover issue</title>
</head>

<body>
<div data-ng-app="myApp" data-ng-controller="defaultCtrl" style="margin: 100px 100px">
    <button custom-popover ng-click="showPopover()">Popover</button>

    <script type="text/ng-template" id="example.html">
        <p>My name is {{user.name || 'undefined' }}</p>
    </script>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script src="//code.angularjs.org/1.3.8/angular-sanitize.min.js" data-semver="1.3.8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-strap/2.1.5/angular-strap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-strap/2.1.5/angular-strap.tpl.min.js"></script>
<script type="text/javascript">
    var app = angular.module("myApp", ['mgcrea.ngStrap', 'ngSanitize']);
    app.controller("defaultCtrl", ["$scope", function($scope) {
        $scope.user = {
            name: "Roman"
        };
    }]);
    app.directive("customPopover", ["$popover", "$compile", function($popover, $compile) {
        return {
            restrict: "A",
            scope: true,
            link: function(scope, element, attrs) {
                var myPopover = $popover(element, {
                    title: 'My Title',
                    contentTemplate: 'example.html',
                    html: true,
                    trigger: 'manual',
                    autoClose: true
                });
                scope.showPopover = function() {
                    myPopover.show();
                }
            }
        }
    }]);
</script>
</body>
</html>

谢谢指教

结帐http://plnkr.co/edit/62BDv7JwluOl3eqtXPCZ?p=preview

原型继承在 angular 范围内是默认的。

因此,如果您不创建独立作用域,那么您可以直接从您的作用域访问父作用域对象,除非您不覆盖它们。

 var myPopover = $popover(element, {
                    title: 'My Title',
                    contentTemplate: 'example.html',
                    html: true,
                    trigger: 'manual',
                    autoClose: true,
                    scope: scope
                });
                scope.showPopover = function() {
                    myPopover.show();
                }