简体   繁体   中英

Can I have the angular controller and the directive in separate JS files?

I am using angular 1.5.x .

I currently have two files , one has the directive and the other the controller that the directive uses.

directive.js

(function(){
    var myApp = angular.module('legalentity');
  myApp.directive("banks", function() {
        return {
            controller: bankController,
            template: "<div ng-include='banks-tab.html'></div>"
        };
    });
}());

I have a separate file that has the BankController defined.

(function () {

    var myApp = angular.module("legalentity");

    myApp.controller("bankController", 'BankController');

    BankController.$inject = ['RDS_BASE_URL'];

    function BankController(RDS_BASE_URL) {
        var entityID = 1001;
        $scope.bankGrid = {
            dataSource: RDS_BASE_URL + '/entity/' + entityID + '/bankdetails/',
            filterRow: {
                visible: true
            },
            headerFilter: {
                visible: true
            },
            groupPanel: {
                visible: true
            }
        };
    }
}());

My page does not load as the directive cannot find the bankController Error as below ReferenceError: bankController is not defined

Please can you advise how this can be fixed? I would like to keep the controller and the directive in separate JS files.

Try this:

controller: 'bankController'

Also, instead of this line:

myApp.controller("bankController", 'BankController');

Write this:

myApp.controller("bankController", BankController);

Here's an explanation of what's going on:

When you write controller: bankController, it tries to find an object called bankController in your directive.js where it's not able to find it. But when you say 'bankController' it tries to find an object with this name in the current module. And although it's in a different file angular is able to find it and use it.

In the second case if you say

myApp.controller("bankController", 'BankController');

It tries to assign a string to a controller which I believe should result in a js error (try checking your console) and so your controller will not even get created due to this error. Instead we assign it BankController which is a function it CAN find in the file and use it as the controller definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM