AngularJS:如何与其他控制器共享范围函数和变量

时间:2015-03-23 14:16:10

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

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

$scope.alert = null;

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

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

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

2 个答案:

答案 0 :(得分:4)

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

<强>控制器

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注入该控制器的范围,然后在大括号内,您可以将公共控制器范围分配给控制器的当前范围。

使用公共控制器

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数据,您可以通过在控制器中注入服务名称来使用此服务方法。

服务

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);

});

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

答案 1 :(得分:0)

我对这个用例的解决方案是定义一种观察者模式。

代码的结构如下:

var app = angular.module('testModule', []);
app.factory('alertService', ['$timeout', function($timeout){
    var alertListeners = [];

    this.register = function (listener) {
        alertListeners.push(listener);
    };

    this.notifyAll = function (data) {
    for (// each listener in array) {
        var listenerObject = alertListeners[i];
        try { // do not allow exceptions in individual listeners to corrupt other listener processing
            listenerObject.notify(data);
        } catch(e) {
            console.log(e);
        }   
    }
    };
 }]).
 directive('myAlerts', ['alertService', function(alertService){

     var alertDirectiveObserver = function($scope, alertService) {

        this.notify = function(data) {
        /*
         * TO DO - use data to show alert
         */
         };

         /*
          * Register this object as an event Listener. Possibly supply an event key, and listener id to enable more resuse
          */
         alertService.register(this);

         $scope.on('$destroy', function() {
             alertService.unregister(// some listener id);
         });
     };


   return {
     restrict: 'A',
     template: '<div ng-class="alertClass" ng-show="alertNeeded">{{alertMessage}}</div>',
     controller: ['$scope', 'alertService', alertDirectiveObserver],
     link: function(scope){  
     }
    }
}]).
controller('alertShowingController', ['$scope', 'alertService',   function($scope, alertService){
    alertService.notifyAll({'warning', 'Warning alert!!!'})   
 ]);

alertShowingController是一个简单的示例,说明所有控制器如何简单地注入alertService并生成事件。

我自己的实现更精细,因为它使用单独的事件键来允许控制器生成其他事件通知。

然后我可以定义一个位于页面顶部固定位置的div,它会调度自举警报。

<div my-alerts ng-repeat="alert in alertList" type="{{alert.type}}" close="closeAlert(alertList, $index)">{{alert.msg}}</div>
相关问题