我有一个调用服务的控制器。在服务中,我执行$rootScope。$broadcast在页面加载时完美工作。但是,当我再次调用该服务时,$rootScope。$broadcast似乎没有被调用。
控制器:
app.controller('MyController', function($scope, myService) {
myService.inititate($scope);
$scope.Next = function () {
myService.next($scope);
};
});
服务:
app.service("loginService", function ($http, $rootScope) {
var counter = 0;
var checkuser = function (scope) {
//some code.....
$rootScope.$broadcast('rcvrCast', counter + 1);
}
this.inititate = function (scope) {
//some code.....
checkuser(scope);
};
this.next = function (scope) {
//some code.....
checkuser(scope);
};
);
指令:
app.directive('myDirective', function() {
return {
restrict: 'A',
replace: true,
scope: {},
link: function(scope, element, attrs) {
scope.$on("rcvrCast", function(event, val) {
scope.myValue = val;
});
},
template:
'<section>' +
'<p>{{myValue}}</p>' +
'</section>'
}
});
HTML: <body ng-controller="ParentController">
<section my-directive></section>
<div ui-view></div>
</body>
index.html
页面加载MyController
控制器。
加载页面时,从this.inititate
调用的$broadcast
被成功调用,{{myValue}}
显示为1。
然而,点击我的按钮有ng-click="Next()"
,虽然服务再次被调用,{{myValue}}
仍然显示为1,而不是1 + 1 = 2。
任何想法吗?
您没有使用计数器计数。试着用++counter
代替counter+1
app.service("loginService", function ($http, $rootScope) {
var counter = 0;
var checkuser = function (scope) {
//some code.....
$rootScope.$broadcast('rcvrCast', ++counter);
}
this.inititate = function (scope) {
//some code.....
checkuser(scope);
};
this.next = function (scope) {
//some code.....
checkuser(scope);
};
);