Keval Patel
Keval Patel

Reputation: 995

How to create common function for alert in angularjs

I am working on angularJS, and I want to create common alert function, so I can use it in all controllers for validations and other purposes.

my service is,

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);

Controller calling services and I am able to see alert div contents on screen

My view is,

<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>

Here, I have common template created, and I am assigning "alertMessage" and "showAlert", which is working fine. But what I should write in place of " ???whichName??? " controller.

Because I want to use same service from different controllers. but when I call "hideAlert()" action, where it needs to go and execute?

We cannot write serviceName in ng-Controller directory.

So what I need to change in my code to make it work ?

Upvotes: 0

Views: 1293

Answers (1)

floribon
floribon

Reputation: 19193

If you want to keep everything in the $rootScope, you can add it your service as well:

$rootScope.CommonSrv = CommonSrv;

You can then access hideAlert directly from this service in the HTML, you do not need any ng-controller. Here is the template:

<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>

And to be clean, I would recommend to keep the alertMessage and showAlert within this service rather than in the root scope, it then becomes:

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

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

And the 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>

Upvotes: 2

Related Questions