简体   繁体   中英

how to call the same function from two different places in angularjs

I have two different HTML files. Select Button is there in two html files. If I click that button I need to select the card.

  • I have two functions. First one is by default i need to show in screen.

  • Second one is I need to show the same data in a popup modal.

    1. home.html
 <button type="button" class="btn btn-primary col-xs-12 col-md-12 col-lg-12"
         ng-click="selectCard()">ADD CARD</button>
  1. page.html
<button type="button" class="btn btn-primary col-xs-12 col-md-12 col-lg-12" 
        ng-click="selectCard()">ADD CARD</button>

These both are same html code.

  1. mainController.js
$scope.selectCard = function () {
    $scope.select = true;               
}

But my problem is,

page. html file is in popup modal.

$scope.view = function () {
    $uibModal.open({
        templateUrl: 'page.html',
        size: 'lg',
        windowClass: 'page',
        controller: function ($scope, $uibModalInstance, $timeout) {          
          $scope.selectCard = function(){             
              $scope.select = true;
          }
        }
    });
}

Here inside popup modal also I need to write the same function again. Then only it is working.

Is any way is there to use the same function in both places.

For common functions, services are the best places. You should add your service as Dependency Injection as required in your controllers.

To create and inject service you can refer to this official angularjs documentation site: https://docs.angularjs.org/guide/services

You can move the function to separate service and inject it in all places you need.

In case it should be bound to mainController.js , service function can use rxJs Subject or just emit event to update value in mainController.js .

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