Angular Inject on parent scope
by Julien Roche
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<body ng-controller="MainController">
<my-directive name="$firstDirective" ng-click="$firstDirective.notify()">First directive</my-directive>
<br />
<br />
<fieldset ng-if="isVisible">
<legend>My directive under a ng-if</legend>
<my-directive name="$secondDirective" ng-click="$secondDirective.notify()">Second directive</my-directive>
</div>
</body>
CSS
my-directive {
background-color: yellow;
border: 1px solid black;
color: black;
cursor: pointer;
display: inline-block;
text-align: center;
width: 300px;
}
JavaScript
angular
.module('myApp', [])
.controller('MainController', function ($scope) {
$scope.isVisible = true;
})
.directive('myDirective', function ($interpolate) {
return {
'restrict': 'E',
'scope': { },
'link': function ($scope, $element, $attrs) {
var $parentScope = $scope.$parent;
var name = $interpolate($attrs.name)($parentScope);
$parentScope[name] = {
'notify': function () {
alert('Notify for ' + name);
}
};
$element.on('$destroy', function () {
delete $parentScope[name];
});
}
}
});
angular.bootstrap(document.body, ['myApp']);