Reputation: 2202
I have this controller:
.controller('UserListEditorController', function ($scope) {
$scope.status = {
isopenFields: false,
isopenFilters: false
};
$scope.toggleDropdownFields = function($event) {
$scope.status.isopenFields = !$scope.status.isopenFields;
};
$scope.toggleDropdownFilters = function($event) {
$scope.status.isopenFilters = !$scope.status.isopenFilters;
};
})
And I have this directive:
.directive('myDraggable', ['$document', function($document) {
return {
link: function(scope, element, attr) {
element.on('mousedown', function(event) {
element.data('mousedown', true);
});
element.on('focusin', function(event) {
if (element.data('mousedown')) {
Calling $scope.toggleDropdown
}
});
}
};
}]);
How do I call a function that is in controllers $scope from the custom directive?
Upvotes: 0
Views: 72
Reputation: 2349
You can use scope.toggleDropdownFields()
if your directive scope is not isolated and if the directive is called inside the scope of the controller UserListEditorController
.
Please refer
Html
<button ng-controller="MyCtrl" dir>I just met you</button>
Angular
var app = angular.module('plunker', []);
app.directive('dir', function ($parse) {
return {
restrict: 'A',
scope: true,
link: function (scope, element, attrs) {
element.bind('click', function (e) {
scope.click();
});
}
};
});
app.controller('MyCtrl',function($scope) {
$scope.click = function () {
console.log("Whatever you want to do");
};
});
Upvotes: 0
Reputation: 21901
You have create a directive type of shared scope
so if you define a directive with shared scope you can directly access the properties of the ng-controller
just as,
scope.sayHello();
here is the DEMO
may be you have gone wrong with calling element.data..
, in angular directive you can access the attribute you put to the element as attr.mousedown
Here is a good Series to Refer
Upvotes: 3
Reputation: 28318
This is one way of doing it:
Markup:
<button ng-controller="SomeCtrl" my-directive call-me="callMeMaybe()">I just met you</button>
JS:
var app = angular.module('myApp', []);
app.directive('myDirective', function ($parse) {
return {
restrict: 'A',
scope: true,
link: function (scope, element, attrs) {
element.bind('click', function (e) {
scope.$apply(attrs.callMe);
});
}
};
});
function SomeCtrl($scope) {
$scope.callMeMaybe = function () {
alert('I just called you, maybe');
};
}
Upvotes: 0