1

I would like to extend some module with UI-logic.

For example - simple modul, who can add alerts and clear alerts. And use it in other modules.

var MessageBox = angular.module('MessageBox', ['ui.bootstrap']);

MessageBox.controller('MessageBoxController', ['$rootScope', function ($rootScope) {
    $rootScope.alerts = [];
    $rootScope.addAlert = function (alert) {
        $rootScope.alerts.push(alert);
    };
    $rootScope.closeAlert = function (index) {
        $rootScope.alerts.splice(index, 1);
    };
}]);

End Using in another module:

var App = angular.module('App', ['MessageBox']);

... and controller:

console.log("$scope.alerts : " + $scope.alerts);
addAlert({type: 'success', msg: 'Message.'});

Is it best practices for extending modules and functions?

P.S. please rank this question, I can't get 15 reputation. Thanks!

yazabara
  • 1,253
  • 4
  • 21
  • 39

1 Answers1

0

In short no. Adding functions and data structures to the rootScope will eventually fall apart on you. It's pretty much just globals which is a terrible way to design software because it creates high coupling. It's much better to use Services that can encapsulate data and methods. Define your functions and data that you wish to share across modules/controllers/etc in a Service then you can simply inject those Services into other places that want to use them.

chubbsondubs
  • 37,646
  • 24
  • 106
  • 138