Reputation: 197
I have this controller
.controller('MyCtrl', ['$scope', '$rootScope', 'restService',
function ($scope, $rootScope, restService) {
$scope.saveTask = function (workflow, form) {
if (form.$valid) {
if (workflow.isSaved == false) {
angular.toJson(workflow);
$rootScope.$broadcast('saveOrDelete', 1); /*HERE IS CALLING*/
};
}
};
}
]);
And my directive with saveOrDelete
function:
.directive('logWork', [function() {
return {
restrict: 'AE',
link: function(scope, element, attrs) {
scope.saveOrDelete = function(option) {
switch (option) {
case 1: {
angular.element(element).find('.note-input').css('width', '85%');
angular.element(element).find('.active-accept-button').css('display', 'none');
angular.element(element).find('.active-delete-button').css('display', 'inline-block');
} break;
case 2: {
angular.element(element).find('.note-input').css('width', '70%');
angular.element(element).find('.active-accept-button').css('display', 'inline-block');
angular.element(element).find('.active-delete-button').css('display', 'inline-block');
} break;
};
};
},
templateUrl: Global.directives.worklogblock
};
}])
And I have a problem, I can't call my saveOrDelete
function from controller. How I can do this? Please help me to solve this issue.
Upvotes: 0
Views: 363
Reputation: 4766
In your directive you need to listen to the saveOrDelete
event your emitting in your controller. You then have access to the arguments passed into the broadcast
or emit
and can work with them.
$scope.$on('saveOrDelete', function(event, option) { $scope.saveOrDelete(option); });
Be aware anything in your application will be fired if they are listening to this event.
Not too sure if your aware of the difference between broadcast
and emit
, there listed in the docs below. They can give strange behavior if your not aware, thought i best mention it also.
EDIT: On a side note your wrapping your element in angular.element
i don't think this is entirely necessary. If you have JQuery included before angular then the element object will be a full JQuery object. If not it will be a JQueryLite object.
Emit and broadcast docs, you will also find the docs on listening to events ($on
) on this page: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$emit
Upvotes: 2
Reputation: 933
You are using the $broadcast wrong.
$scope.$on('saveOrDelete', function(event, option) {
switch (option) {
case 1: {
angular.element(element).find('.note-input').css('width', '85%');
angular.element(element).find('.active-accept-button').css('display', 'none');
angular.element(element).find('.active-delete-button').css('display', 'inline-block');
} break;
case 2: {
angular.element(element).find('.note-input').css('width', '70%');
angular.element(element).find('.active-accept-button').css('display', 'inline-block');
angular.element(element).find('.active-delete-button').css('display', 'inline-block');
} break;
};});
Upvotes: 0