StackOverflow_20885065: access-parent-scope-in-angular-directive-with-template
Illustration of answer to http://stackoverflow.com/questions/20885065/access-parent-scope-in-angular-directive-with-template.
by ExpertSystem
HTML
<div ng-controller="OuterCtrl">
<div ng-controller="InnerCtrl">
<editor ng-model="content"
my-items="items"></editor>
<hr />
<editor2 ng-model="content"></editor2>
</div>
</div>
JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('OuterCtrl', function ($scope) {
$scope.items = ['one', 'two', 'three'];
});
myApp.controller('InnerCtrl', function ($scope) {
$scope.content = {
title: 'Hi, there !',
text: 'This is some text...'
};
});
myApp.directive('editor', function () {
return {
restrict: 'E',
scope: {
content: '=ngModel',
items: '=myItems'
},
template:
'<input ng-model="content.title" /><br />' +
'<textarea ng-model="content.text"></textarea> <br />' +
'<div style="border:1px solid black;">' +
'<div style="background-color:gray;">' +
'{{content.title}}' +
'</div>' +
'<div>{{content.text}}</div>' +
'Binding through attribute: ' +
'<select ng-model="selectedItem" ' +
'ng-options="item for item in items"></select>' +
'</div>'
};
});
myApp.directive('editor2', function () {
return {
restrict: 'E',
scope: {
content: '=ngModel'
},
template:
'<input ng-model="content.title" /><br />' +
'<textarea ng-model="content.text"></textarea> <br />' +
'<div style="border:1px solid black;">' +
'<div style="background-color:gray;">' +
'{{content.title}}' +
'</div>' +
'<div>{{content.text}}</div>' +
'Binding through `link` function: ' +
'<select ng-model="selectedItem" ' +
'ng-options="item for item in items"></select>' +
'</div>',
link: function (scope, element, attrs) {
scope.items = scope.$parent.items;
}
};
});