简体   繁体   English

具有功能的角度扩展模块(最佳实践)

[英]angular extending modules with functions(best practices)

I would like to extend some module with UI-logic. 我想用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? 是扩展模块和功能的最佳实践吗?

PS please rank this question, I can't get 15 reputation. PS请对这个问题进行排名,我无法获得15点声望。 Thanks! 谢谢!

In short no. 简而言之,没有。 Adding functions and data structures to the rootScope will eventually fall apart on you. 向rootScope添加功能和数据结构最终将使您分崩离析。 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. 定义您希望跨服务的模块/控制器/等共享的功能和数据,然后您可以将这些服务简单地注入到其他想要使用它们的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM