Search code examples
javascriptjqueryangularjsdatetimepicker

AngularJS $apply with scope var raises exception


I am trying to do a very basic example. A datetimepicker with a binding to a simple text.

html

<body ng-app="testApp">
    <div ng-controller="testCtrl as ctrl">
        <p><h1>{{ctrl.text}}</h1></p>
        <p>-----------------------------</p>
        <input id="datetimepicker" type="text">
        <p>{{ctrl.result}}</p>
    </div>
</body>

js

var testController = angular.module('testApp.testModule', []);

testController.controller('testCtrl', [function () {
    var myScope = this;
    myScope.text = '#### Controls binding test ####';

    jQuery('#datetimepicker').datetimepicker({
        onChangeDateTime: function (dp, $input) {
            myScope.$apply(function () {
                myScope.result = $input.val();
            });
        }
    });
}]);

When I run the following exception is raised: enter image description here

http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

I am using the alternative 'new' control naming using a var scope instead of $scope, and tried to just replace $scope with myScope, but with no success.

AngularJS v1.2.24 jQuery DateTimePicker plugin v2.2.5 jQuery JavaScript Library v2.1.1


Solution

  • this should do the job

    var testController = angular.module('testApp.testModule', []);
    
    testController.controller('testCtrl', [ '$scope', function ($scope) {
        this.text = '#### Controls binding test ####';
        var vm = this; //viewModel
        jQuery('#datetimepicker').datetimepicker({
            onChangeDateTime: function (dp, $input) {
                $scope.$apply(function () {
                    vm.result = $input.val();
                });
            }
        });
    }]);