【发布时间】:2013-01-29 10:04:59
【问题描述】:
我想编写一个具有隔离作用域的指令,但也想让该作用域可用于父作用域的控制器。我找到了这个解决方案:
<div ng-controller="Main">
<popupbutton directive-scope="popup"></popupbutton>
</div>
app.directive('popupbutton', [function() {
return {
restrict: "E",
scope: {
directiveScope: "="
},
link: function(sc, el, attrs) {
sc.directiveScope = sc;
sc.testvalue = 'foo';
}
};
}]);
app.controller('Main', function($scope) {
alert($scope.popup.testvalue); // Where did the property 'popup' come from?!?
});
见Plunker。
我觉得这有点难看,因为它涉及在 HTML 中编写一个属性,而在控制器的代码中,您无法分辨范围属性的来源。有没有更好的方法来做到这一点?
编辑:
此外,似乎 $scope.popup 在控制器“Main”运行时甚至都不可用。指令的链接功能还没有执行?
【问题讨论】:
-
您根本不应该从控制器访问指令的范围。可能有更好的方法来做到这一点 - 你的用例是什么?
-
指令创建一个按钮和一个可以通过单击按钮打开的弹出框。我希望父控制器查看盒子是否打开。该指令的范围还包含打开和关闭盒子的方法,父控制器也应该可以访问这些方法。
标签: angularjs