How to reuse a function in multiple controllers

I have several controllers for several routes:

app.controller('FirstController', function ($scope) { $scope.func = function () { console.log('route 1'); } } app.controller('SecondController', function ($scope) { $scope.func = function () { console.log('route 2'); } } ... 

and a directive that uses $scope.func in this way:

 app.directive('thedirective', function () { return { link: function (scope, $element, attrs) { $scope.func(attrs.thedirective); } } }); 

$scope.func is different in every controller. I expect $ scope.func to register โ€œroute 1โ€ when we are in route1, and FirstController is the current controller and register โ€œroute 2โ€ on route 2, but only โ€œroute 1โ€ is what I get in the console . could you tell me why changing a route does not change the $ scope directive?

+7
angularjs angularjs-service angularjs-directive
source share
2 answers

The isolated scale was what I used to reuse a function that is defined differently by several controllers. According to the docs, when you highlight the scope of directives, for example:

 scope: { myIsolatedFunc: '=' } 

Angular will look for the current scope for the property named as the value of the element's myIsolatedFunc property. which means:

if you have a function called $scope.func1 and an element defined as:

 <div myIsolatedFunc="func1"> 

and on a different route with a different controller, a function like $scope.func2 , along with an element defined as:

 <div myIsolatedFunc="func2"> 

you can use both functions in the directive:

 app.directive('thedirective', function () { return { scope: { myIsolatedFunc: '=' }, link: function (scope, $element, attrs) { $scope.myIsolatedFunc(attrs.thedirective); } } }); 

not to mention the need to have different names for different functions.

+2
source share

In AngularJS, if the controllers use a regular function.

Best practice is to use a service or factory that will enter the controller.

 app.factory('commonService', function ($scope) { var obj= {}; obj.func = function () { console.log('route 1'); } obj.func1 = function () { console.log('route 2'); } return obj; } app.controller('FirstController', function ($scope,commonService) { console.log('route 1' + commonService.func()); } app.controller('SecondController', function ($scope,commonService) { console.log('route 2' + commonService.func1()); } 

And when we talk about the directive, the scope of the directive will be with a single controller or a directive controller, or an external controller that we defined.

 <div ng-controller="firstController"> <your-directive /> </div> <div ng-controller="secondController"> <your-directive /> </div> 
+5
source share

All Articles