Tuximo
Tuximo

Reputation: 57

How to use a controllerAs syntax within a directive template in AngularJS

Here is my controller:

angular
    .module('app')
    .controller('MyCtrl', MyCtrl);

Viewer.$inject = [];

function MyCtrl() {
  var vm = this;
  vm.titles = ['Hello', 'world'];
}

My Directive:

angular
    .module('app')
    .directive('myDirective', myDirective);

myDirective.$inject = [];

function flPagesArea($compile) {

    var directive = {
        link: link,
        restrict: 'EA',
        template: '<div ng-repeat="title in vm.titles">{{title}}</div>'
    };
    return directive;
}

The result is:

<!-- ng-repeat= title in vm.titles -->

Is the problem with my usage of the controller as or I'm missing something. Thank you.

Upvotes: 0

Views: 194

Answers (1)

Use the controllerAs option and the bindToController property. Also check the name of the function associated to directive. In your case, you never associate the flPagesArea function to directive declaration in the module.

    angular
    .module('app')
    .directive('myDirective', myDirective);

myDirective.$inject = ['$compile'];

function myDirective($compile) {

    var directive = {
        link: link,
        restrict: 'EA',
        template: '<div ng-repeat="title in vm.titles">{{title}}</div>',
        controller: 'MyCtrl',
        controllerAs: 'vm',
        bindToController: true
    };
    return directive;
}

Upvotes: 1

Related Questions