0

I am creating a web app in which I want to validate some of my input fields

so I am using $emit and $on to keep it short

I created a directive which looks like this

angular.module('myapp').directive('validateFields', function () {
    return function (scope, element, attrs) {
        scope.$on('validateInputFields', function (param) {
            if (param == undefined || param == null || param == '') {
                return true;
            } else {
                return false;
            }
        });
    }
});

I want to execute this directive and return true or false as per result(I know this is incorrect but I am very new in directives and $emit $on)

and I am calling this in my controller

$scope.$emit('validateInputFields', $scope.mddoh);

but this is printing an object

{name: "validateInputFields", targetScope: b, stopPropagation: ƒ, preventDefault: ƒ, defaultPrevented: false, …}

what is the best way to use $emit and $on in my scenerio

1 Answers1

0

Change $scope.$emit in your Controller to

$rootScope.$broadcast('validateInputFields', $scope.mddoh);

and in your Directive, change scope.$on to

$rootScope.$on

and don't forget to inject $rootScope.

holydragon
  • 6,158
  • 6
  • 39
  • 62
  • can you please tell me the difference between broadcast and emit –  Oct 24 '18 at 08:02
  • see https://stackoverflow.com/questions/26752030/rootscope-broadcast-vs-scope-emit and https://stackoverflow.com/questions/37717493/usage-of-broadcast-emit-and-on-in-angularjs – holydragon Oct 24 '18 at 08:12