Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put user defined functions in Angular JS?

In my view, I want to render:

<p>   {{ say() }} </p> 

Where say is defined as such:

say = function() {   return "Hello World"; } 

I can define it in my controller:

function TestCtrl($scope) {   $scope.say = function() { ... }; } 

But then it's only accessible within that controller.

If I define the function outside the Angular file structure, it renders nothing. Same if I define it in my controllers.js file, but outside a controller function scope.

Where is the proper place to put my function, so I can render it in any controller?

like image 563
Kyle Macey Avatar asked Sep 18 '12 15:09

Kyle Macey


People also ask

Where we use user-defined function?

User-defined functions are functions that you use to organize your code in the body of a policy. Once you define a function, you can call it in the same way as the built-in action and parser functions.

How can use user-defined function in JavaScript?

JavaScript UDFs are UDFs that run in the browser on a webpage that has an embedded Excel workbook. You use the JavaScript UDF inside of the embedded workbook. As long as you are working with the workbook in the browser, you can use the JavaScript UDF just like you use the built-in Excel functions.

Which keyword is used to declare a user-defined function?

In Python, def keyword is used to declare user defined functions. An indented block of statements follows the function name and arguments which contains the body of the function.


1 Answers

One way is to create a service with the functions you want to share across multiple controllers. See this post for more info.

After you do so you can inject the service you created into any controller and access the say() function with code something like this:

function TestCtrl($scope, myService){    $scope.say = myService.say; } 

Where you defined myService as:

angular.module('myApp', [])     .factory('myService', function () {         return {             say: function () {                 return "Hello World";             }         }     }); 

Here is a jsFiddle with an example.

like image 113
Gloopy Avatar answered Sep 17 '22 12:09

Gloopy