简体   繁体   中英

$rootscope.$broadcast with $on

I have issue with Angular js I am calling on function with in html controller

    <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.

You're calling test2() each time you click:

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. Just call it once, and test that test() broadcasts the event and is handled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM