Вопрос по – AngularJS - jQuery UI - проблема с привязкой

8

В настоящее время я портирую большое приложение на веб-приложение на основе HTML5 - я начал создавать приложение на AngularJS и наслаждаюсь мощью фреймворка AngularJS - у меня сейчас стоит одна проблема:

У меня есть директива, которая дает мне jQuery Datepicker, однако привязка к модели не работает.

http://jsfiddle.net/9BRNf/

Я, вероятно, неправильно понимаю, как работают директивы, и хотел бы посмотреть, смогу ли я исправить эту часть моего понимания структуры. Я просмотрел множество примеров (включая проект angularui на github, но все еще не понимал, почему привязка не происходит)

Любая помощь будет принята с благодарностью.

Error: User Rate Limit Exceeded user577537
Error: User Rate Limit Exceeded dj2
Error: User Rate Limit Exceeded dj2
Error: User Rate Limit Exceededjsfiddle.net/9BRNf/2Error: User Rate Limit Exceeded Dinesh Copoosamy
Error: User Rate Limit Exceeded Dinesh Copoosamy

Ваш Ответ

7   ответов
6

Error: User Rate Limit Exceeded

$.datepicker.setDefaults({
    // When a date is selected from the picker
    onSelect: function(newValue) {
        if (window.angular && angular.element)
            // Update the angular model
            angular.element(this).controller("ngModel").$setViewValue(newValue);
    }
});

Error: User Rate Limit ExceededpriorError: User Rate Limit Exceeded.datepicker()Error: User Rate Limit Exceeded

(Taken from another answer I posted here: Error: User Rate Limit Exceeded)

4

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceededjsfiddle.net/9BRNf/6Error: User Rate Limit Exceeded Dinesh Copoosamy
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
2

Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededError: User Rate Limit Exceeded jsFiddle: Error: User Rate Limit ExceededError: User Rate Limit Exceeded


// Code inspired by angular-ui https://github.com/angular-ui/angular-ui/blob/master/modules/directives/date/src/date.js
/*
Features:
* via the ui-date attribute:
    * Ability to say how model is parsed into a date object
    * Ability to say how input's value is parsed into a date object
    * Ability to say how a date object is saved to the model
    * Ability to say how a date object is displayed in the input
* via the ui-date-picker attribute
    * Ability to directly configure the jQuery-ui datepicker
*/


angular.module('ui.directives', [])
    .directive('uiDate', function () {
        return {
            require: '?ngModel',
            //scope: {},
            link: function ($scope, element, attrs, ngModel) {
                // Date Handling Functions
                var dateHandler = $.extend({ model: {}, view: {} }, $scope.$eval(attrs.uiDate));

                // This will attempt to use preferredParser to parse a date.
                function defaultDateParse(date, preferredParser) {
                    if (!preferredParser)
                        return new Date(date);
                    return preferredParser(date);
                }

                // This will attempt to use preferredFormatter to format a date, otherwise use 'mm/dd/yy'.
                function defaultDateFormatter(date, preferredFormatter) {
                    if (!preferredFormatter)
                        preferredFormatter = "mm/dd/yy";

                    if (typeof preferredFormatter == 'string')
                        return $.datepicker.formatDate(preferredFormatter, date);
                    else
                        return preferredFormatter(date);
                }

                // Functions for Parsing & Formatting on the Model & View
                function parseDateFromModel(date) {
                    return defaultDateParse(date, dateHandler.model.parse)
                }
                function parseDateFromView(date) {
                    return defaultDateParse(date, dateHandler.view.parse)
                }
                function formatDateForModel(date) {
                    return defaultDateFormatter(date, dateHandler.model.format)
                }
                function formatDateForView(date) {
                    return defaultDateFormatter(date, dateHandler.view.format)
                }

                var defaultDateViewFormat = (
                    typeof dateHandler.view.format == 'string'
                    ? dateHandler.view.format
                    : 'mm/dd/yy'
                )

                // Initialize the jQuery-ui datePicker
                var datePickerSettings = $.extend({ dateFormat: defaultDateViewFormat }, $scope.$eval(attrs.uiDatePicker))
                var oldOnSelect = datePickerSettings.onSelect;
                datePickerSettings.onSelect = function (dateVal) {
                    $scope.$apply(function () {
                        element.focus().val(dateVal);
                        updateModel();
                    })
                    if (oldOnSelect)
                        oldOnSelect.apply(this, arguments)
                }

                element.datepicker(datePickerSettings);

                if (ngModel) {
                    // Specify how UI should be updated
                    ngModel.$render = function () {
                        element.val(ngModel.$viewValue || '');
                    };

                    // Listen for change events to enable binding
                    element.bind('blur keyup change', function () {
                        $scope.$apply(updateModel);
                    });

                    // Write data to the model
                    function updateModel() {
                        ngModel.$setViewValue(element.val());
                    }

                    // Convert the model into a string value
                    ngModel.$formatters.push(function (v) {
                        if (v != "" && v != null)
                            return formatDateForView(parseDateFromModel(v));
                        return null;
                    });

                    // Convert the string value into the model
                    ngModel.$parsers.push(function (v) {
                        if (v != "" && v != null)
                            return formatDateForModel(parseDateFromView(v))
                        return null;
                    });
                }

            }
        };
    })
Error: User Rate Limit Exceeded
1

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

     var myApp = angular.module('myApp', ['myApp.directives']);


    function MainCtrl() {

    }

    angular.module('myApp.directives', [])
      .directive('myDatepicker', function() {
          return {
             require: '?ngModel',
                link: function (scope, element, attrs, ngModelCtrl) {
          element.datepicker({
             changeYear : true,
             changeMonth : true,
             appendText : '(yyyy-mm-dd)',
             dateFormat : 'yy-mm-dd',
              onSelect: function(date) {
                  ngModelCtrl.$setViewValue(date);
                            scope.$apply();
              }
          });
        }
      }

  });
2

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

var myApp = angular.module('myApp', ['myApp.directives']);

function MainCtrl($scope) {

    $scope.deepValue = {
        fromDate: null,
        toDate: null
    }

}

angular.module('myApp.directives', [])
  .directive('myDatepicker', function() {
    return function(scope, element, attrs) {     

       element.datepicker({
         changeYear : true,
         changeMonth : true,
         appendText : '(yyyy-mm-dd)',
         dateFormat : 'yy-mm-dd', 
                onSelect: function(dateText) {                    
                    var mdlAttr = $(this).attr('ng-model').split(".");

                    if (mdlAttr.length > 1) {

                        var objAttr = mdlAttr[mdlAttr.length-1];
                        var s = scope[mdlAttr[0]];

                        for (var i=0; i < mdlAttr.length-2; i++) {
                            s = s[mdlAttr[i]];
                        }

                        s[objAttr] = dateText;
                    } else {
                        scope[mdlAttr[0]] = dateText;
   ,                 }

                    scope.$apply();
                }                
        });

    }
});​
Error: User Rate Limit Exceeded
0

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Html:

<input id="StartDate" data-ng-model="viewModel.startdate" date-from />

Directive:

app.directive('dateFrom', function() {
    return function (scope, element, attrs) {
        var doDate = $('#EndDate');
        element.datepicker({
          dateFormat: 'dd-M-yy', showOtherMonths: true, 
          selectOtherMonths: true, minDate: '0',
          beforeShowDay: function (date) {
              var day = date.getDay();
              console.log(scope.nosunday);
              if (scope.nosunday === 'true') return [(day !== 0), '']; // disable sundays
              else return [true, ''];
          },
          onSelect: function (selectedDate) {
              var toDate = new Date(element.datepicker("getDate"));
              toDate.setDate(toDate.getDate() + 1);
              doDate.datepicker('option', 'minDate', toDate);
              scope.viewModel.startdate = selectedDate;
              scope.viewModel.enddate = doDate.val();
          }
        });
    }
})

Error: User Rate Limit Exceeded

0

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

HTML

<input id="date1" value="1/1/1980"  ng-model="fromDate" my-datepicker />
<input id="date2" value="1/1/1980" ng-model="toDate" my-datepicker />

JavaScript

angular.module('myApp.directives', [])
  .directive('myDatepicker', function() {
    return function(scope, element, attrs) {     

       element.datepicker({
         changeYear : true,
         changeMonth : true,
         appendText : '(yyyy-mm-dd)',
         dateFormat : 'yy-mm-dd', 
            onSelect: function(dateText) {                    
                var mdlAttr = $(this).attr('ng-model');
                scope[mdlAttr] = dateText;                    
                scope.$apply();                                                   
            }                
        });

    }
  });
Error: User Rate Limit Exceeded

Похожие вопросы