我想编写一个具有隔离范围的指令,但也想让该范围可用于父范围的控制器。我找到了这个解决方案:
<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”运行时甚至都不可用。指令的链接功能还没有执行?