Integrating Angular with legacy code

Have an old app you wish would just go away. Here is an example of how you can breathe new life into it with Angular.

by manoj

HTML

<script src="http://code.angularjs.org/1.1.0/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="baseController" id="baseController-div">
        baseController.X = {{x}}<br/>
        <a ng-click="incrementDataInService()">incrementDataInService</a><br>     
    </div>
    <hr/>
        
         <button type="button" onclick="externalCall()">Legacy call from within view</button>
        
    <div ng-controller="mainController" id="mainController-div">
        mainController.X = {{x}}<br/>
        <a ng-click="incrementDataInService()">incrementDataInService</a><br>
        
           <div ng-controller="subController" id="subController-div">
             subController.X = {{x}}<br/>
             <a ng-click="incrementDataInService()">incrementDataInService</a><br>
               
                 <div ng-controller="microController" id="microController-div">
                  microController.X = {{x}}<br/>
                  <a ng-click="incrementDataInService()">incrementDataInService</a><br>     
                 </div>
                              
           </div>
                
     </div>
</div>

        <button type="button" onclick="externalCall()">Legacy Call from outside of view</button>

JavaScript

angular.module('myApp', [])
    .service('myService',  function ($rootScope) {
        var x=5 ;
        return {
            increase : function() {
                x++;
                $rootScope.$broadcast('XChanged', x);
            }
       };
    })

function baseController($scope, myService) {
    $scope.x = 1;
    $scope.incrementDataInService= function() {
        
        myService.increase();
        // if you are calling from legacy code, you will need to invoke $apply()
        $scope.$apply();
    }     
    $scope.$on('XChanged', function(event, x) {
        $scope.x = x;
    });        
}
    
function mainController($scope, myService) {
   $scope.x = 1;
    $scope.incrementDataInService= function() {
        myService.increase();            
    }
    $scope.$on('XChanged', function(event, x) {
        $scope.x = x;
    });           
}

function subController($scope, myService) {
   $scope.x = 1;
    $scope.incrementDataInService= function() {
        myService.increase();            
    }
    $scope.$on('XChanged', function(event, x) {
        $scope.x = x;
    });           
}
function microController($scope, myService) {
   $scope.x = 1;
    $scope.incrementDataInService= function() {
        myService.increase();  
         $scope.$apply();
    }
    $scope.$on('XChanged', function(event, x) {
        $scope.x = x;
     
    });           
}

function externalCall(){
 
    angular.element($("#microController-div")).scope().incrementDataInService();
      
    
}