I want to write a directive with isolated scope but also want to make that scope available for the parent scope\'s controller. I found this solution:
To maintain proper separation of concerns, you should not mix scopes. Not to mention that it will be hard to synchronize. To summarize: your directive should not know anything about the parent scope (or its controller) and your controller should not know anything about a directive's internals. They are separate components in separate layers.
The proper way to communicate between a controller and a directive is through directive attributes. In the case of a popup, say, this can be done with a simple boolean value.
The controller and directive:
app.directive('popupbutton', [function() {
return {
restrict: "E",
scope: { isOpen: "=" },
template: 'ToggleOpen? {{isOpen}}'
};
}]);
app.controller('MainCtrl', function($scope) {
$scope.isOpen = false;
});
And the markup:
This method requires no logic, works out of the box, and maintains clean separation of concerns. Here's an updated plunker: http://plnkr.co/edit/otIaGCLmiNdGcYEgi60f?p=preview
讨论(0)