I
I
Icic Bender2016-07-23 13:57:28
Angular
Icic Bender, 2016-07-23 13:57:28

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';
            }
        };
    });

Main pattern:
<!-- … -->
<div block="example"></div>
<!-- … -->

Template (blocks/example.html):
<div ng-controller="ExampleCtrl as example">
    <p ng-bind="example.text"></p>
</div>

Controller:
angular
    .module('app')
    .controller('ExampleCtrl', ExampleCtrl);
function ExampleCtrl() {
    this.text = 'Текст'
}

Essence The
template is successfully inserted, but for some reason it ignores the attribute ng-controller="ExampleCtrl as example"in the first element of the template, which is why it <p ng-bind="example.text"></p>remains empty.
If you create a directive with replace: false, then the controller will work, but the wrapper will remain.
Or if the attribute is shifted one level lower in the template, then the controller will also work:
<div>
    <div ng-controller="ExampleCtrl as example">
        <p ng-bind="example.text"></p>
    </div>
</div>

Is it because the directive creates its own scope?
Is there any easy way to force a directive to use controller scope without creating extra wrappers?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2016-07-23
@miraage

For these purposes, there is ng-include.

N
napa3um, 2016-07-23
@napa3um

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 question

Ask a Question

731 491 924 answers to any question