Angularjs - 无法读取属性' split'未定义的

时间:2014-05-03 14:22:22

标签: javascript ruby-on-rails angularjs

我正在尝试拆分使用文本字段输入的日期。我想把它放在一个数组中。

在html文件中

<%= text_field_tag :checkoutdate, params[:checkoutdate],:placeholder => 'Select Date', :class=>'form-control datepicker input-lg',:required=>true,"ng-model" => "checkoutdate"%>

    <p class='bg-danger' ng-show="isInvalidDate()">Check-out date cannot be lesser than check-in date</p>

在Controller js文件中

App.controller('validationController',['$scope', function($scope){
$scope.isInvalidDate = function(){
     var checkin = $scope.checkindate.split('-');
     var checkout = $scope.checkoutdate.split('-');

    if($scope.checkin[0]>$scope.checkout[0] || $scope.checkin[1]>$scope.checkout[1]){
        return true;
    }

}

我在控制台中收到错误

Cannot read property 'split' of undefined

我做错了什么?

1 个答案:

答案 0 :(得分:4)

当尚未定义值时,您正在进行脏检查。在运行函数之前,只需检查以确保值不是undefined

App.controller('validationController', ['$scope',
        function ($scope) {
            $scope.isInvalidDate = function () {
                if($scope.checkindate === undefined || $scope.checkoutdate === undefined){
                    return false;
                }
                var checkin = $scope.checkindate.split('-');
                var checkout = $scope.checkoutdate.split('-');

                if ($scope.checkin[0] > $scope.checkout[0] || $scope.checkin[1] > $scope.checkout[1]) {
                    return true;
                }

            }]);