Answer the question
In order to leave comments, you need to log in
How to make a controller work from a template inserted by a directive?
There is a spherical directive in vacuum:
angular
.module('app')
.directive('block', function () {
return {
replace: true,
restrict: 'A',
templateUrl: function (element, attr) {
return 'blocks/' + attr.block + '.html';
}
};
});
<!-- … -->
<div block="example"></div>
<!-- … -->
<div ng-controller="ExampleCtrl as example">
<p ng-bind="example.text"></p>
</div>
angular
.module('app')
.controller('ExampleCtrl', ExampleCtrl);
function ExampleCtrl() {
this.text = 'Текст'
}
ng-controller="ExampleCtrl as example"
in the first element of the template, which is why it <p ng-bind="example.text"></p>
remains empty. replace: false
, then the controller will work, but the wrapper will remain. <div>
<div ng-controller="ExampleCtrl as example">
<p ng-bind="example.text"></p>
</div>
</div>
Answer the question
In order to leave comments, you need to log in
stackoverflow.com/questions/22575424/angularjs-ng-...
But it's better not to overcomplicate with custom directive binding to specify the controller in the template, but simply specify the controller in the directive module.
angular
.module('app')
.directive('block', function () {
return {
replace: true,
restrict: 'A',
templateUrl: function (element, attr) {
return 'blocks/' + attr.block + '.html';
},
controller: 'ExampleCtrl',
controllerAs: 'example',
bindToController: true
};
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question