Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: calling controller function inside a directive link function using &

We're running into a problem trying to call a function passed into a directive using the ampersand '&' in our directive's link function.

It seems the function is called on the controller but no arguments are passed in the call. All the examples we have seen involve passing through by creating a call in template. Is there a way to call a function on your directive from its template, then do something in the directive that calls the controller function passed into it?

like image 594
Walt Avatar asked May 30 '13 14:05

Walt


People also ask

Which directive is used for controller in angular?

AngularJS ng-controller Directive The ng-controller directive adds a controller to your application. In the controller you can write code, and make functions and variables, which will be parts of an object, available inside the current HTML element. In AngularJS this object is called a scope.

What is the difference between controller and link in directives in AngularJS?

The link option is just a shortcut to setting up a post-link function. controller: The directive controller can be passed to another directive linking/compiling phase. It can be injected into other directices as a mean to use in inter-directive communication.

What does $compile do in AngularJS?

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

What is controller in angular8?

AngularJS Controllers AngularJS applications are controlled by controllers. The ng-controller directive defines the application controller. A controller is a JavaScript Object, created by a standard JavaScript object constructor.


1 Answers

Are you passing the arguments inside {}s? E.g., inside the directive's link function, you'll want to call the method like so: scope.someCtrlFn({arg1: someValue});

<div my-directive callback-fn="ctrlFn(arg1)"></div> 
app.directive('myDirective', function() {     return {         scope: { someCtrlFn: '&callbackFn' },         link: function(scope, element, attrs) {             scope.someCtrlFn({arg1: 22});         },     } });  function MyCtrl($scope) {     $scope.ctrlFn = function(test) {         console.log(test);     } } 

Fiddle.

like image 142
Mark Rajcok Avatar answered Oct 04 '22 10:10

Mark Rajcok