$timeout example

Showing an arbitrary example of how to use $timeout to get around looking at $$phase.

by Steven Lambert

HTML

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://code.angularjs.org/1.2.18/angular.min.js"></script>
<div id="controller" ng-controller="myCtrl">
    <div>Angular - {{myVar}}</div>
    <div>jQuery - <span id="jQuery"></span>
    </div>
    <br/>
    <button ng-click="ngClickCall()">Call from Angular</button>
    <button id="outside">Call from Angular</button>
</div>

JavaScript

angular.module('myApp', []);

angular.module('myApp')
    .controller('myCtrl', function ($scope, $timeout) {
    $scope.myVar = 'default val.';

    // function may be called from Angular or from another source
    $scope.myFunc = function myFunc(theVar) {
        // should I $apply or shouldn't I?
        $scope.myVar = theVar;
        
        // $apply
        //if ($scope.$$phase || $scope.$root.$$phase) {
        //$scope.myVar = theVar;
        //} else {
        //    $scope.$apply(function() {
        //        $scope.myVar = theVar;
        //    });
        //}
        
        
        // $timeout
        //$timeout(function() {
        //  $scope.myVar = theVar;
        //});
        
        $('#jQuery').html(theVar);
    };

    $scope.ngClickCall = function ngClickCall() {
        $scope.myFunc('ng-click call.');
    };
});

// could be from a 3rd party async call
$('#outside').on('click', function () {
    angular.element('#controller').scope().myFunc('outside call.');
});