如何与其他控制器共享作用域函数和变量

如何与其他控制器共享作用域函数和变量

本文介绍了AngularJS:如何与其他控制器共享作用域函数和变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've multiple controllers in my application, where I have some duplicate code like:

$scope.alert = null;

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

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

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

What is the recommended way sharing these scope functions and variables in AngularJS? Using controller inheritance?

推荐答案

创建一个控制器,然后将通用方法放在该控制器范围内.这样您就可以在其他任何地方使用该作用域并访问控制器内的方法.

Create a one controller and then place common methods inside that controller scope. So that you can use that scope anywhere else and get access to method inside 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注入它来使用这个控制器的范围,然后在大括号内你可以将通用控制器范围分配给控制器的当前范围.

Thereafter use scope of this controller by inject it using $controller, and then inside curly brace you could assign common controller scope to the current scope of 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

});

或者更准确的方法是使用公共可共享服务,公开两个方法和 alert 数据,您可以通过在控制器中注入服务名称来使用此服务方法.

Or more precise way would be using common sharable service, that exposed two method and alert data, you can use this service method by injecting service name inside your controller.

服务

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

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

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

控制器内部服务的利用

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

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

});

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

Hope this has cleared your concept, Thanks.

这篇关于AngularJS:如何与其他控制器共享作用域函数和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:14