简体   繁体   中英

How to update $scope using jquery?

I have a bootstrapper datepicker. I am updating the value of textbox in hide event. Textbox values changes successfully however $scope doesn't update.

Javascript

 <script type="text/javascript">
        $(document).ready(function () {
            $('#btnAdd').datepicker({
                changeMonth: true,
                changeYear: true,
                numberOfMonths: 1,
                dateFormat: 'dd/mm/yy'
            }).on('hide', function (e) {
                $('#hdnDays').val($(this).val());
                $(this).val('Add');
            });
        })

    </script>

HTML

<input type="text" ng-model="c" id="hdnDays" />
<input type="button" class="btn btn-primary" id="btnAdd" value="Add" />

you can see that I am using ng-model="c" which means $scope.c should change, but it is not happening.

How to update $scope variable from hide event?

in angular, DOM manipulation is done inside of a directive , this is becuase you get two important variables you could use in there, and will solve your problem:

  • you get a variable referencing your element, this way you do not have to relay on it's id, or some other selector,

  • most important, you get a reference to the scope of the element, and this way you could call scope.$apply() when changes have been made in scope variables.

in your case, you should put your code in a directive, something like this:

app.directive('datePicker', function($parse) {
    return {
    restrict: 'E',
    link: function (scope, element, attr) {
        element.datepicker({
            changeMonth: true,
            changeYear: true,
            numberOfMonths: 1,
            dateFormat: 'dd/mm/yy'
        }).on('hide', function (e) {
            scope.$apply(function(){
                $parse(attr['ng-model'])(scope).assign(element.val());
                element.val('Add');
            });
        });
    }
  };
});

and in the view:

<input type="button" class="btn btn-primary datePicker" value="Add" />

you might need to adjust this code depending on what it is exactly you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM