Thomas
Thomas

Reputation: 2137

Reusable components in angular controller

I am trying to create a reusable component for my controllers which can be used multiple times in different controllers.

See plunker: http://plnkr.co/edit/Lc4z4L?p=preview

The problem shown in the plunker is, that in the FirstCtrl the same message is shown than in the SecondCtrl.

How can I achieve some kind of isolated scope with the service? Or am I using the wrong concepts?

Upvotes: 0

Views: 143

Answers (1)

Manny D
Manny D

Reputation: 20714

While it's true a service only has a single instance, you can also return a function which you can then new in your controller which will give you an individual instance of that function:

app.service('alertService', function($timeout) {  
  return function () {
    // assign this to service only because I'm lazy
    var service = this;
    var timeout;

    // start with empty array holding the alerts.
    service.alert_list = [];

    // method to add an alert
    // alert_obj is a object with members type = ( success | info | warning | danger )
    // and msg which is the message string 
    service.addAlert = function (alert_obj) {
        service.alert_list = [];
        service.alert_list.push(alert_obj);
        $timeout.cancel(timeout);
        timeout = $timeout(service.clearAlerts, 5000);
    };

    service.clearAlerts = function clearAlerts() {
        service.alert_list = [];
    };
  }
});

Your updated controller would now look like this:

app.controller('SecondCtrl', function($scope, alertService, $timeout) {

  $scope.alertService = new alertService();

  $scope.alertService.addAlert({"type": "info", "msg": "Infomessage II"});

  $scope.name = 'World II';
});

Updated plunker: http://plnkr.co/edit/RhJbbxj4XxdwY6GAest9?p=preview

Upvotes: 2

Related Questions