我的控制器在其范围中声明一个变量。我希望这个变量在$ rootscope中可以访问。$ on,但似乎并非如此。那是我的问题。
这是我的控制器:
app.controller('MainCtrl', function($rootScope, OnTest) {
$scope.variable = null;
$rootScope.$on('eventCalled', function() {
if ($scope.variable == null) {
alert("THIS IS MY ISSUE: SHOULD NOT BE NULL");
}
});
$scope.methodCalledFromTheView = function () {
$scope.variable = {age: 23};
TestApp.method1();
}
});
这是我的服务:
app.service('TestApp', function ($rootScope) {
this.method1 = function () {
$rootScope.$emit("eventCalled");
}
});
输出:
"这是我的问题:不应该为null"
我应该更改以确保$ scope。可在$ rootscope内到达。$ on?
这是用于更多基于事件的双向绑定的解决方案。同样,凭借$emit
的工作方式,它仅将事件发送到$ Rootscope而不是所有孩子。$广播更适合应用于控制器或指令(DOM中嵌套的任何内容),而$ emit更适合服务,因为服务通常不会创建孤立范围。
// CONTROLLERS SHOULD NOT ACCESS $ROOTSCOPE, BUT USE THEIR OWN $SCOPE
app.controller('MainCtrl', function($scope, TestApp) {
$scope.variable = null;
TestApp.broadcastEventCalled();
TestApp.onEventCalled($scope, function() {
$scope.variable = {age: 23};
if ($scope.variable == null) {
alert("THIS IS MY ISSUE: SHOULD NOT BE NULL");
}
});
});
//SERVICE SHOULD ONLY HAVE EVENT THROWERS AND $ROOTSCOPE
app.service('TestApp', function ($rootScope) {
this.broadcastEventCalled = function () {
$rootScope.$broadcast("eventCalled");
};
this.onEventCalled = function (scope, callback) {
return scope.$on('eventCalled', function () {
callback();
});
};
});
希望它有帮助!