我试图在$scope服务的AngularJS中创建一些通常有用的扩展:
(此代码在所有控制器之外定义):
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(),我的应用程序也不再工作了。我看不出我做错了什么。很明显,我的错误隐藏在眼前吗?
发布于 2015-02-17 09:58:26
我使用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.");这很管用!
谢谢你的回答!
发布于 2015-02-17 09:45:15
如前所述,on -> $on和
this.$apply(fn);它应该是:
$scope.$apply(fn);以及:
var phase = this.$root.$$phase;应:
var phase = $scope.$root.$$phase; // or $scope.$$phase;但是,我会重写您的代码来使用$timeout,因为角的摘要周期并不是固定的。
$timeout(function() {
// code to by "apply'ed" to be digested next cycle
});https://stackoverflow.com/questions/28558539
复制相似问题