7

I have a date picker widget, and I want to pass the picked date to the controller. I have this script snippet in my view:

        <div id="datepicker"></div>
        <script type="text/javascript">
        $('#datepicker').datepicker();
        $('#datepicker').datepicker()
        .on('changeDate', function(ev){

          alert(ev.date);
        });
        </script>

How to send this "ev.date" to the controller?

I want it to affect controller variable so this change is then picked up by a directive and dom is modified in the directive.

2
  • You can try using the angular event bus and fire an event. Commented Jun 2, 2013 at 19:05
  • This tells me nothing :( I only started with angularjs yesterday. Can you post an example on how to send data to a variable in controller? Commented Jun 2, 2013 at 19:06

1 Answer 1

10

You can do something like this:

$('#datepicker').datepicker()
  .on('changeDate', function(ev){
     //get a hold of controller and scope
     var element = angular.element($('#datepicker'));
     var controller = element.controller();
     var scope = element.scope();

     //as this happends outside of angular you probably have to notify angular of the change by wrapping your function call in $apply
     scope.$apply(function(){
       scope.updateDateFunction(ev.date);
     });
 });

See: http://docs.angularjs.org/api/angular.element

Sign up to request clarification or add additional context in comments.

2 Comments

I have created an updateDateFunction definition in the controller: $scope.updateDateFunction = function (date){ $scope.pickedDate = date; }; and used your code, unfortunately it does not work and gives the following error: Object [object Object] has no method 'updateDateFunction' The function is not misspelled.
You put the function on the $scope, not the controller (which is normal, I'll update my code to fit your structure)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.