javascript - AngularJS:如何与其他 Controller 共享作用域函数和变量

标签 javascript angularjs angularjs-scope angularjs-service angularjs-controller

我的应用程序中有多个 Controller ,其中有一些重复的代码,例如:

$scope.alert = null;

$scope.addAlert = function (message) {
    $scope.alert = { type: 'danger', msg: message };
};

$scope.clearAlerts = function () {
    $scope.alert = null;
};

在 AngularJS 中共享这些作用域函数和变量的推荐方式是什么?使用 Controller 继承?

最佳答案

创建一个单一 Controller ,然后将通用方法放入该 Controller 范围内。这样您就可以在其他任何地方使用该范围并访问 Controller 内部的方法。

Controller

app.controller('commonCtrl', function($scope) {
    $scope.alert = null;

    $scope.addAlert = function(message) {
        $scope.alert = {
            type: 'danger',
            msg: message
        };
    };

    $scope.clearAlerts = function() {
        $scope.alert = null;
    };
});

此后通过使用 $controller 注入(inject)它来使用此 Controller 的作用域,然后在大括号内您可以将通用 Controller 作用域分配给 Controller 的当前作用域。

通用 Controller 的使用

app.controller('testCtrl', function($scope, $controller) {
    //inject comomon controller scope to current scope , 
    //below line will add 'commonCtrl' scope to current scope
    $controller('commonCtrl', { $scope: $scope }); 
    //common controller scope will be available from here

});

或者更精确的方法是使用公共(public)共享服务,它公开了两个方法和alert数据,您可以通过在 Controller 中注入(inject)服务名称来使用此服务方法。

服务

app.service('commonService', function($scope) {
    this.alert = null;

    this.addAlert = function(message) {
        this.alert = {
            type: 'danger',
            msg: message
        };
    };

    this.clearAlerts = function() {
        this.alert = null;
    };
});

Controller 内部服务的使用

app.controller('testCtrl', function($scope, commonService) {

  console.log(commonService.alert);
  commonService.addAlert("Something");
  console.log("Updated Alert" + commonService.alert);

});

希望这已经清除了您的概念,谢谢。

关于javascript - AngularJS:如何与其他 Controller 共享作用域函数和变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29212545/

相关文章:

javascript - 气质 `nestRemoting()`有时找不到关系

angularjs - 如何限制在 ng-repeat 中显示的行?

javascript - AngularJS 10 $digest() 迭代达到列表显示时

javascript - 从 1.2.x 更新后,指令不从 Controller ($scope)链接

javascript - Google Apps 脚本中的正则表达式

javascript - 在 first 完成后执行 jQuery 函数

javascript - 将 svg 的 div 保存为 pdf

javascript - 使用 md-virtual-repeat 动态加载字体

Javascript 拼接删除错误的项目

angularjs - 如何在具有隔离范围的指令中监听站点范围的事件