[英]$rootscope.$broadcast with $on
I have issue with Angular js I am calling on function with in html controller 我在html控制器中使用Angular js调用函数时遇到问题
<button class="btn" ng-click="test()"> Save</button>
<button class="btn" ng-click="test();test2()"> New</button>
$scope.test= function(){
$http.put(settings.WebApiBaseUrl + 'api/myfile/' , {
headers: {
'X-ApiKey': myKey
}
}).success(function (data) {
$rootScope.$broadcast('data:saved')
$scope.loading = false;
}).error(function (data, status, headers, config) {
$scope.loading = false;
});
}
and other function i called 和其他我调用的功能
$scope.test2=function(){ $scope.$on('data:saved', function (event,tags)
{
$http.post(settings.WebApiBaseUrl + 'api/myfile/' , {
headers: {
'X-ApiKey': myKey
}
}).success(function (data) {
$scope.loading = false;
}).error(function (data, status, headers, config) {
$scope.loading = false;
});
}}
If i click once it work fine but ii click second time it looping second function two time. 如果我单击一次,它可以正常工作,但ii单击第二次,则第二次循环第二个功能。
You're calling test2()
each time you click: 您每次单击都在调用test2()
:
ng-click="test();test2()"
which subscribes to the event each time: 每次订阅该事件:
$scope.test2=function(){
$scope.$on('data:saved', function (event,tags)
You only want to subscribe once, so test2()
shouldn't be called each time you click. 您只想订阅一次,因此不应每次单击都调用test2()
。 Just call it once, and test that test()
broadcasts the event and is handled. 只需调用一次,然后测试test()
广播事件并进行处理即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.