0
votes

I am new to Angular and just wondering how come my directive is accessible between controller as I only register it into sub controller, not main app controller. Below is my code.

app.module.js

angular.module('adminPage', ['ngRoute', 'ui.bootstrap', 'ngAnimate', 'login', 'registerEmployee', 'listEmployee'])
    .controller('adminPageCtrl', ['$scope', '$location' , funcAdminPageCtrl]);
angular.module('login',[]);
angular.module('registerEmployee', []);
angular.module('listEmployee', []);

So as stated, I have adminPage acts as a main controller and others as sub controllers.

registerEmployeeController.js

angular.module('registerEmployee')
    .controller('registerEmployeeCtrl', ['$scope', funcRegisterEmployeeCtrl
    ])
    .directive("compareTo", ['$timeout', funcCompareTo]);

As seen above, I register the compareTo directive to registerEmployee sub controller.

I would like to use the same directive in listEmployeeController.js's ModalInstanceCtrl (popup), so I added the same directive to that. When I tested it, I got error which is Error: [$compile:multidir] Multiple directives [compareTo, compareTo] asking for new/isolated scope on:. The code is below.

angular.module('listEmployee')
    .controller('listEmployeeCtrl', ['$scope', '$uibModal', '$log', '$document', funcListEmployeeCtrl   ])
    .controller('ModalInstanceCtrl', funcModalInstanceCtrl)
    .directive("compareTo", ['$timeout', funcCompareTo]);

After that I tried removing the compareTo directive from listEmployeeController.js and the error is gone. It is, then, working as expected (the compareTo directive can be used in listEmployeeView.html's modal) even though it is not registered to its controller.

My funcCompareTo is as below.

function funcCompareTo($timeout) {
    return {
        require: "?ngModel",
        scope: {
            otherModelValue: "=compareTo"
        },
        link: function(scope, element, attributes, ngModel) {
            $timeout(function(){

                if (!ngModel) {
                    console.log("can't get ngModel.");
                    return;
                }
                ngModel.$validators.compareTo = function(modelValue) {
                    console.log(modelValue+"; "+scope.otherModelValue);
                    if (modelValue == '') return true;
                    return modelValue == scope.otherModelValue;
                };

                scope.$watch("otherModelValue", function() {
                    ngModel.$validate();
                });

            }, 0);
        }
    };
}

As I only registered the directive in registerEmployeeCtrl, how come that directive is existed in ModalInstanceCtrl?

you seem to be confusing modules with controllers. you don't register directives with specific controllers, you register them once to a module, and they are usable anywhere that module is injected into the app. - Claies
@Claies that makes sense. Thank you for the explanation, appreciate it! - Darren Christopher