javascriptangularjsangularjs-directiveangularjs-serviceangularjs-factory

Re-Usable Angularjs Code


I have scope function ClickA and ClickB in my controller CtrlA, I want to re-use ClickA and ClickB with there containing scope variables "a" and "b" in almost every other controllers, I mean, I simply want to make available these click functions and its containing variables to other controllers without redefining them. It may be possible with services/factory but have no idea to work with them or its directory don't know, can someone suggest me with an example please and yes after injecting/calling these code they should become part of $scope variable for the respective controller.

angular.module("App").controller("CtrlA", function($scope)
{

$scope.ClickA = function(){

$scope.a =true;
$scope.b = false;
}


$scope.ClickB = function(){

$scope.a =false;
$scope.b = true;
}

});
<button ng-click="ClickA()"/>
{{a}}<br>
{{b}}

<button ng-click="ClickB()"/>
{{a}}<br>
{{b}}

Solution

  • Create a service:

    app.service("service", function() {
        this.ClickA = function(){
            this.a = true;
            this.b = false;
        }
        this.ClickB = function(){
            this.a = false;
            this.b = true;
        }
    })
    

    In the controller, bind to $scope:

    $scope.serviceClickA = service.ClickA.bind($scope);
    $scope.serviceClickB = service.ClickB.bind($scope);
    

    The DEMO

    angular.module("app",[])
    .controller("ctrl", function($scope, service) {
        $scope.ClickA = function(){
            $scope.a = "ClickA";
            $scope.b = false;
        }
        $scope.ClickB = function(){
            $scope.a = false;
            $scope.b = "ClickB";
        }
        $scope.serviceClickA = service.ClickA.bind($scope);
        $scope.serviceClickB = service.ClickB.bind($scope);
    })
    .service("service", function() {
        this.ClickA = function(){
            this.a = "ServiceClickA";
            this.b = false;
        }
        this.ClickB = function(){
            this.a = false;
            this.b = "ServiceClickB";
        }
    })
    <script src="//unpkg.com/angular/angular.js"></script>
      <body ng-app="app" ng-controller="ctrl">
          <button ng-click="ClickA()">ClickA</button>
        <br/>
          <button ng-click="ClickB()">ClickB</button>
        <hr/>
          a= {{a}}
        <br/>
          b= {{b}}
        <hr/>
          <button ng-click="serviceClickA()">serviceClickA</button>
        <br/>
          <button ng-click="serviceClickB()">serviceClickB</button>      
      </body>