我正在尝试以编程方式创建popover,但遇到以下问题。我无法在弹出模板中访问父作用域。预期结果是:
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>
感谢您的建议
答案 0 :(得分:9)
结帐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();
}