![](/img/trans.png)
[英]How do i make callbacks on functions activated by ng-click in angular?
[英]How do I implement a global function that can be used across multiple ng-click functions in angular
我有一个简单的示例function checkIfValueIsGreaterThan0
如果我具有ng-click
函数,则可以这样使用它:
<div ng-click="checkIfValueIsGreaterThan0()"></div>
但是然后我需要在$ scope中声明此函数。 有没有一种方法可以将其添加到可在我的应用程序中使用的全局库中,并且能够注入该库并使它从我的角度运行而不必像在控制器中那样显式声明它?
$scope.checkIfValueIsGreaterThan0 = myLibrary.checkIfValueIsGreaterThan0
在您的应用程序引导程序中,在运行或配置块中,将其设置在$rootScope
(应自行注入)上:
$rootScope.checkIfValueIsGreaterThan0 = myLibrary.checkIfValueIsGreaterThan0;
由于$rootScope
是应用程序中所有范围的父级,因此您将可以在任何模板中使用checkIfValueIsGreaterThan0()
或在任何控制器中使用$scope.checkIfValueIsGreaterThan0()
。
是的,这绝对是可能的,您可以使用它进行出厂服务并在您的应用程序中使用它。 您可能需要将$ scope或$ http服务传递给您的工厂,但这取决于您要完成的工作。 如果你这样做,那么你可以像我在下面的控制器中那样做
var app = angular.module( 'myApp' ,[]);
app.factory(' checkIfValueIsGreaterThan0', function()
{
var checkIfValueIsGreaterThan0 = {};
checkIfValueIsGreaterThan0.test = function()
{
// Do ur stuff here and return it
}
return checkIfValueIsGreaterThan0;
});
当您想使用此工厂时,只需将其注入到ur控制器中并调用它,然后如您所说,您便可以将其分配给$ scope,您可以按照以下步骤进行操作。
app.controller( 'myCtrl' , ['$scope', 'checkIfValueIsGreaterThan0', function($scope, checkIfValueIsGreaterThan0)
{
$scope.whatever = checkIfValueIsGreaterThan0.test();
}]);
希望您能理解,如果有任何拼写错误,对此我深感抱歉,我正在尝试通过移动Fone进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.