简体   繁体   English

如何实现可在angular中跨多个ng-click函数使用的全局函数

[英]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 我有一个简单的示例function checkIfValueIsGreaterThan0

If I have an ng-click function I can use it like this: 如果我具有ng-click函数,则可以这样使用它:

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

But I then need this function declared in my $scope. 但是然后我需要在$ 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 (应自行注入)上:

$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.. 由于$rootScope是应用程序中所有范围的父级,因此您将可以在任何模板中使用checkIfValueIsGreaterThan0()或在任何控制器中使用$scope.checkIfValueIsGreaterThan0()

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. 您可能需要将$ scope或$ http服务传递给您的工厂,但这取决于您要完成的工作。 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. 当您想使用此工厂时,只需将其注入到ur控制器中并调用它,然后如您所说,您便可以将其分配给$ scope,您可以按照以下步骤进行操作。

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. 希望您能理解,如果有任何拼写错误,对此我深感抱歉,我正在尝试通过移动Fone进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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