How do i access This
of controller inside of directive and its template when not using isoloted scope?
app.controller('ChildCtrl', function() {
this.name = "Name from children";
});
Simple parse it as controller as instance value
into your directive scope like in this simple fiddle demo:
<div ng-controller="MyCtrl as ctrl">
Hello, <span simple-directive data="ctrl.name"></span>!
</div>
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
this.name = 'Superhero';
});
myApp.directive('simpleDirective', function () {
return {
restrict: 'A',
scope: {
data: '='
},
template: '{{ data }}',
link: function (scope, elem, attrs) {
console.log(scope.data);
}
}
});
An other approach is to just parse your controller into the directive by using controller:'MyCtrl as ctrl'
like in this demo fiddle.
Hello, <span simple-directive></span>!
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
this.name = 'Superhero';
});
myApp.directive('simpleDirective', function () {
return {
restrict: 'A',
controller:'MyCtrl as ctrl',
template: '{{ ctrl.name }}'
}
});
You can also parse the hole controller instance to in scope and access it like in this demo fiddle.
<div ng-controller="MyCtrl as ctrl">
Hello, <span simple-directive ctrl="ctrl"></span>!
<br />
<input type="text" ng-model="ctrl.name">
</div>
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
this.name = 'Superhero';
});
myApp.directive('simpleDirective', function () {
return {
restrict: 'A',
scope: {
ctrl: '='
},
template: '{{ ctrl.name }}',
link: function (scope, elem, attrs) {
}
}
});