добавление к существующему массиву при нажатии просто очищает массив, почему?

Еще один вопрос angularJS. У меня есть область действия, привязывающая щелчок, который должен добавить одно значение при первом щелчке и другое значение при втором щелчке, но он просто продолжает возвращать пустой массив и снова заполнять первое значение, почему? :

scope.dbclickalert = function (scope, $watch) {
    var getCheckInDate = this.cellData.date;
    var formatcheckindate = new Date(getCheckInDate);
    var checkingdates = [];
    var curr_datecell = formatcheckindate.getDate();
    var padded_day = (curr_datecell < 10) ? '0' + curr_datecell : curr_datecell;
    var curr_monthcell = formatcheckindate.getMonth() + 1;
    var padded_month = (curr_monthcell < 10) ? '0' + curr_monthcell : curr_monthcell;
    var curr_yearcell = formatcheckindate.getFullYear();
    var date_stringcell =  + padded_month + "/" + padded_day + "/" + curr_yearcell;
    var checkindatestrg = "checkindate";
    console.log(checkingdates.length);
    if (checkingdates.length < 2) {
        alert("element exists in array");
        checkingdates.push('checkoutdate');
        checkingdates.push(date_stringcell);
        console.log(checkingdates + checkingdates.length);
    } else {
        checkingdates.push('checkindate');
        checkingdates.push(date_stringcell);
    }
    var setCheckInDate = el.hasClass('checkInDate');
    if (checkingdates === true) {
        alert('You have allready set your check In Date');
    } else {
        el.addClass('checkInDate');
        $('#checkoutbar').addClass('datePickerchecout');
    }
    $(".date-cell").each(function removeclasses() {
        $(this).removeClass('true');
    });
    return getCheckInDate;
};

хорошо, поэтому, когда я объявляю это вне функции, я получаю неопределенную ошибку:

   scope.checkingdates = [];
      scope.dbclickalert = function(scope, $watch){
         var getCheckInDate = this.cellData.date;
         var formatcheckindate = new Date(getCheckInDate);
         var checkingdates = scope.checkingdates;
         var curr_datecell = formatcheckindate.getDate();
         var padded_day = (curr_datecell < 10) ? '0'+curr_datecell : curr_datecell;
         var curr_monthcell = formatcheckindate.getMonth() + 1;
         var padded_month = (curr_monthcell < 10) ? '0'+curr_monthcell : curr_monthcell;
         var curr_yearcell = formatcheckindate.getFullYear();
         var date_stringcell = + padded_month + "/" + padded_day + "/" + curr_yearcell;
         var checkindatestrg = "checkindate";
         console.log(checkingdates.length);
           if (checkingdates.length < 2){
              alert("element exists in array");
              checkingdates.push('checkoutdate');
              checkingdates.push(date_stringcell);
              console.log(checkingdates+checkingdates.length);
          }else{
              checkingdates.push('checkindate');
              checkingdates.push(date_stringcell);
          }
         var setCheckInDate = el.hasClass('checkInDate');
          if (checkingdates === true){
              alert('You have allready set your check In Date');
          } else{
              el.addClass('checkInDate');
              $('#checkoutbar').addClass('datePickerchecout');
          }
             $(".date-cell").each(function removeclasses() {
                $(this).removeClass('true');
             });
              return getCheckInDate;
      };

хорошо, в третьей версии этого снова те же данные «дата», если был нажат один и тот же div, но не если был нажат второй div с тем же ng-click = «dbclickalert ()», почему?

link: function(scope, el, attributes, dateSheetCtrl, $watch) {
          scope.checkingdatesarry = [];
  scope.dbclickalert = function(){
                 var getCheckInDate = this.cellData.date;
                 var formatcheckindate = new Date(getCheckInDate);
                 var checkingdates = scope.checkingdates;
                 var curr_datecell = formatcheckindate.getDate();
                 var padded_day = (curr_datecell < 10) ? '0'+curr_datecell : curr_datecell;
                 var curr_monthcell = formatcheckindate.getMonth() + 1;
                 var padded_month = (curr_monthcell < 10) ? '0'+curr_monthcell : curr_monthcell;
                 var curr_yearcell = formatcheckindate.getFullYear();
                 var date_stringcell = + padded_month + "/" + padded_day + "/" + curr_yearcell;
                 var checkindatestrg = "checkindate";
                 var checkoutdatestrg = "checkoutdate";


                if( $.inArray('checkindate', scope.checkingdates) !== -1 )  {
                     scope.checkingdatesarry.push(checkoutdatestrg);
                      scope.checkingdatesarry.push(date_stringcell);
                      console.log(scope.checkingdatesarry + scope.checkingdatesarry.length);


                }
                else{
                scope.checkingdatesarry.push(checkindatestrg);
                      scope.checkingdatesarry.push(date_stringcell);
                      console.log(scope.checkingdatesarry + scope.checkingdatesarry.length);


                  }


                 var setCheckInDate = el.hasClass('checkInDate');
                  if (scope.checkingdates === true){
                      alert('You have allready set your check In Date');
                  } else{
                      el.addClass('checkInDate');
                      $('#checkoutbar').addClass('datePickerchecout');
                  }
                     $(".date-cell").each(function removeclasses() {
                        $(this).removeClass('true');
                     });
                     return  scope.checkingdatesarry;
  };

хорошо для всех, кто заботится, ответ заключался в том, что, поскольку мой div был создан с помощью директивы angularJS, он возвращал и массив для каждого div вместо одного глобального массива, я взял массив полностью из директивы и переместил его в службу и это работает нормально.


person vimes1984    schedule 08.08.2013    source источник


Ответы (1)


Потому что вы переопределили массив с пустым списком в действии dbclickalert. Таким образом, каждый раз, когда действие запускается, массив будет пустым.

var checkingdates = [];

Вы должны переместить его за пределы функции и объявить как

$scope.checkingdates = [];  //In your code, you may use scope.checkingdates = []; if you renamed the $scope when you inject it
person zs2020    schedule 08.08.2013
comment
@ vimes1984 используйте scope.checkingdates. вы должны поддерживать переменные, добавляя их в $scope. - person zs2020; 08.08.2013
comment
@vimes1984 vimes1984, когда вы получаете доступ к массиву, вы должны использовать scope.checkingdates.push('checkoutdate'); - person zs2020; 08.08.2013
comment
который по-прежнему возвращает undefined - person vimes1984; 08.08.2013
comment
@ vimes1984 ты заменил все checkingdates на scope.checkingdates? - person zs2020; 09.08.2013
comment
да, я даже переместил его из dbclickalrt, он все равно всегда обновляется как пустой при следующем щелчке - person vimes1984; 09.08.2013
comment
давайте продолжим это обсуждение в чате - person vimes1984; 09.08.2013