扩展 $scope

Extending $scope

我正在尝试为 AngularJS 中的 $scope 服务创建一些通常有用的扩展:

(此代码在所有控制器之外定义):

var ExtendScope = function ($scope) {

    // safeApply is a safe replacement for $apply
    $scope.safeApply = function (fn) {
        var phase = this.$root.$$phase;
        if (phase == '$apply' || phase == '$digest') {
            if (fn && (typeof (fn) === 'function')) {
                fn();
            }
        } else {
            this.$apply(fn);
        }
    };


    // alertOn is shorthand for event handlers that must just pop up a message
    $scope.alertOn = function (eventName, message) {
        $scope.on(eventname, function () { alert(message); });
    };
};

第一个扩展 safeApply() 可以运行,但是当我在上面的代码中添加 alertOn() 时,即使未调用 $scope.alertOn(),我的应用程序也不再运行。对于它的生命,我看不出我做错了什么。我的错误就这么明显吗?

on -> $on 如前所述 和

this.$apply(fn);

应该是:

$scope.$apply(fn);

和:

var phase = this.$root.$$phase;

应该是:

var phase = $scope.$root.$$phase; // or $scope.$$phase;

但是,我会重写您的代码以使用 $timeout,因为 angular 的摘要周期不是一成不变的。

$timeout(function() {
   // code to by "apply'ed" to be digested next cycle
});

我用angular.extend解决了,如下:

"use strict";


// Safely apply changes to the $scope
// Call this instead of $scope.$apply();

var ExtendScope = function ($scope) {

        angular.extend($scope, {
            safeApply: function (fn) {
                var phase = this.$root.$$phase;
                if (phase == '$apply' || phase == '$digest') {
                    if (fn && (typeof (fn) === 'function')) {
                        fn();
                    }
                } else {
                    this.$apply(fn);
                }
            },

            alertOn: function (eventName, message) {
                this.$on(eventName, function () { alert(message); });
            }
        });
};

所以现在在我的控制器中我可以简单地添加,例如,

$scope.alertOn('save_succeeded', "Saved.");

这很有效!

感谢您的回答!