JQueryUI Datepicker 指令在使用 Angular 的 List 删除元素后出现故障.Splice()



JQueryUI日期选择器在使用ng-reeat语句中的Angular list.splice($index,1)删除元素时发生故障。

删除后(使用下面显示的del($index)函数),将显示日历,但它开始为下一个输入选择日期,并为下一输入选择下一个日期。。。

角度控制器:

myApp.controller("CheckList", ["$scope", function ($scope) {
        $scope.items = [];
        ... // add/load function
        $scope.del = function (index) {
            $scope.items.splice(index, 1);
        };
}]);

角度日期选择器指令:

myApp.directive('datepicker', function ($timeout) {
       var linker = function (scope, element, attrs) {
            $timeout(function () {
                element.datepicker({
                    dateFormat: 'dd/mm/yy',
                    changeYear: true
                });
            });
        }
        return {
            restrict: 'A',
            link: linker,
            transclude: true
        }
});

HTML

  <div ng-controller="CheckList" id="divListItems" ng-cloak>
       <div ng-repeat="item in items" >
            <input type="text" datepicker id="CheckList-_{{$index}}_-ValidadeFinal"
                name="CheckList[{{$index}}].ValidadeFinal" ng-model="item.valfinal" />
      </div>
      <button type="button" ng-click="del($index)">Del</button>
 </div>

这是由使用$index在HTML上定义的ID引起的。删除元素后,angular会重新命名并重置字段的ID(由于绑定到$index),并使指令绑定失效。

解决方案:

从HTML输入中删除ID定义,并从指令中删除"transclude=true"。

HTML

   <div ng-controller="CheckList" id="divListItems" ng-cloak>
       <div ng-repeat="item in items" >
            <input type="text" datepicker name="CheckList[{{$index}}].ValidadeFinal"
                 ng-model="item.valfinal" />
      </div>
      <button type="button" ng-click="del($index)">Del</button>
   </div>

JQuery日期选择器指令

myApp.directive('datepicker', function ($timeout) {
   var linker = function (scope, element, attrs) {
        $timeout(function () {
            element.datepicker({
                dateFormat: 'dd/mm/yy',
                changeYear: true
            });
        });
    }
    return {
        restrict: 'A',
        link: linker
    }
});

最新更新