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
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
.