Where to put user defined functions in Angular JS?

后端 未结 1 1911
你的背包
你的背包 2021-01-30 21:40

In my view, I want to render:

{{ say() }}

Where say is defined as such:

say = function() {         


        
相关标签:
1条回答
  • 2021-01-30 22:11

    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.

    0 讨论(0)
提交回复
热议问题