0

I seem to come across an error when I try to define a controller within a directive that is wrapped in an IIFE. Although I could fixed this by adding ng-controller on the div in tableHelper.html. I was wondering the code below returns tableHelperCtrl as undefined.

Using angular.js 1.2.29

app.module.js

(function () {
    'use strict';

    angular.module('app', [

    ]);
})();

tableHelper.controller.js

(function () {
    'use strict';

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

    function tableHelperCtrl() {

        var vm = this;
        vm.data = 'some data'
    }
})();

tableHelper.directive.js

(function () {
    'use strict';

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

    function tableHelper() {

        var directive = {
            restrict: 'A',
            templateUrl: './src/app/tableHelper/tableHelper.html',
            link: link,
            controller: tableHelperCtrl,
            controllerAs: 'vm'

        };
        return directive;
        }
    }
})();

tableHelper.html

<div>
    <p>Table Helpers Directive</p>
    <table>
        <thead></thead>
        <td>{{vm}}</td>
    </table>
</div>
Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

0

You should not assign them the same controller. Give them a controller each and make them communicate through scope (using isolate scopes too if needed) or through a service.

Andrew Donovan
  • 552
  • 2
  • 14
0

There are a couple of issues with your directive code. Suresh's comment about wrapping the name of your controller in quotes seems to be one issue, although I've seen it work without them, I couldn't get it.

You've also got an extra closing curly brace, an you didn't define link although I guess we could assume that you've got it somewhere but left it out.

One more item is since you've defined your controller as 'vm', you want to use vm.data in your html instead of just vm.

Here's a plunker that shows it working with these changes.

Community
  • 1
  • 1
DrewJordan
  • 5,266
  • 1
  • 25
  • 39