简体   繁体   中英

How do I implement a global function that can be used across multiple ng-click functions in angular

I have a simple example function checkIfValueIsGreaterThan0

If I have an ng-click function I can use it like this:

<div ng-click="checkIfValueIsGreaterThan0()"></div>

But I then need this function declared in my $scope. Is there a way to add this to a global library that can be used across my application and be able to inject that library and have it work from my view without having to declare it explicitly like so in my controller?

$scope.checkIfValueIsGreaterThan0 = myLibrary.checkIfValueIsGreaterThan0

In your app bootstrap, in a run or config block, set it on $rootScope (which itself should be injected):

$rootScope.checkIfValueIsGreaterThan0 = myLibrary.checkIfValueIsGreaterThan0;

As $rootScope is the parent of all scopes within your application, you will be able to use checkIfValueIsGreaterThan0() in any template or $scope.checkIfValueIsGreaterThan0() in any controller..

Yes it is most certainly possble, u can make a factory service out of it and use it across ur app. You may need to pass $scope or $http service to ur factory but it depends on what are u trying to accomplish. In case if u do then u can do it like i did it in the controller below

var app = angular.module( 'myApp' ,[]);

app.factory(' checkIfValueIsGreaterThan0',  function()
{
       var checkIfValueIsGreaterThan0 = {};

       checkIfValueIsGreaterThan0.test =  function()
       {
              // Do ur stuff here and return it
       }

       return checkIfValueIsGreaterThan0;
});

When u want to use this factory simply inject it into ur controller and call it, and as u said u wana assign it to the $scope u can do that as following.

app.controller( 'myCtrl' , ['$scope', 'checkIfValueIsGreaterThan0', function($scope, checkIfValueIsGreaterThan0)
{ 
        $scope.whatever = checkIfValueIsGreaterThan0.test();
}]);

I hope u'll get the idea, If there is any typo error i'm sorry for that cuz i'm tryping this from mobile fone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM