2015-04-04 66 views
0

我正在研究angularJS,并且我想创建通用警报函数,因此我可以在所有控制器中将它用于验证和其他用途。如何在angularjs中为警报创建通用函数

我的服务,

JodoModule.service("CommonSrv", function ($rootScope) { 
this.showAlert = function (message, status) { 
    $rootScope.alertMessage = message; 
    $rootScope.showAlert = status; 
} 
this.hideAlert = function() { 
    $rootScope.showAlert = false; 
} 

})

ControllerOne,

$rootScope.CommonSrv = CommonSrv; 
    CommonSrv.showAlert("No notifications available", true); 

ControllerTwo,

$rootScope.CommonSrv = CommonSrv; 
    CommonSrv.showAlert("No data available", true); 

控制器呼叫服务,我能够看到警报DIV屏幕上的内容

我的看法是,

<div ng-show="showAlert" class="alertCustom"> 
    <label>{{alertMessage}}</label> 
    <br /><br /> 
    <a ng-click="CommonSrv.hideAlert()" class="btn btn-warning btn-sm"> 
     &nbsp; <span style="color:brown; font-weight:bold">OK</span> &nbsp; 
    </a> 
</div> 

在这里,我有共同的模板创建的,而我分配“alertMessage”和“showAlert”,这是工作的罚款。但是我应该写什么来代替 “??? which ???”控制器。

因为我想使用来自不同控制器的相同服务。但是当我调用“hideAlert()”动作时,它需要去执行?

我们不能在ng-Controller目录中写入serviceName。

那么,我需要改变我的代码,使其工作?

回答

2

如果你想保持一切都在$rootScope,你可以将其添加为您服务,以及:

$rootScope.CommonSrv = CommonSrv; 

然后,您可以在HTML直接访问hideAlert从这项服务中,你不需要任何ng-controller。这里是模板:

<div ng-show="showAlert" class="alertCustom"> 
    <label>{{alertMessage}}</label> 
    <br /><br /> 
    <a ng-click="CommonSrv.hideAlert()" class="btn btn-warning btn-sm"> 
     &nbsp; <span style="color:brown; font-weight:bold">OK</span> &nbsp; 
    </a> 
</div> 

而且是干净的,我会建议保持这个服务中alertMessageshowAlert,而不是在根范围内,它便成为:

JodoModule.service("CommonSrv", function ($rootScope) { 
    this.showAlert = function (message, status) { 
    this.alertMessage = message; 
    this.showAlert = status; 
    } 

    this.hideAlert = function() { 
    this.showAlert = false; 
    } 
}) 

和HTML :

<div ng-show="CommonSrv.showAlert" class="alertCustom"> 
    <label>{{CommonSrv.alertMessage}}</label> 
    <br /><br /> 
    <a ng-click="CommonSrv.hideAlert()" class="btn btn-warning btn-sm"> 
     &nbsp; <span style="color:brown; font-weight:bold">OK</span> &nbsp; 
    </a> 
</div> 
+0

这是因为'CommonSrv'所需的可访问从HTML,即你需要把它在你的范围:'$ scope.CommonSrv = CommonSrv;'(或在根范围内,如果你想) – floribon 2015-04-04 03:11:59

+0

嘿,这是我的错误......现在它的工作......我写了CommonSrvTemp insted只是CommonSrv ......谢谢...... :) – 2015-04-04 03:13:31