0

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?

3
  • There is no need for it I guess. I just need to know what is a right way to call a function. Html can be just something simple like this: <div myDraggable></div> Commented Sep 8, 2015 at 12:07
  • 1
    can't u use like scope.toggleDropdown() ? Commented Sep 8, 2015 at 12:08
  • 2
    @Tachi If directive is defined descendant of the controller you can use what K.Toress suggested. Commented Sep 8, 2015 at 12:13

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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'); }; } 

Comments

0

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"); }; }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.