简体   繁体   中英

How do i display validation error from controller using angularjs?

I am new to angularjs and totally confused,i am trying below code and dont know if it is right way.

index.html

<div class="input-group" ng-controller="validationController">
    <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span> </span>
    <%= text_field_tag :checkindate, params[:checkindate], :placeholder => 'Select Date',  :class=>'form-control datepicker input-lg',:required=>true,"ng-model" => "checkin.date"%>

</div>


<div class="input-group" ng-controller='validationController'>
    <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span> </span>
    <%= text_field_tag :checkoutdate, params[:checkoutdate],:placeholder => 'Select Date', :class=>'form-control datepicker input-lg',:required=>true,"ng-model" => "checkout.date"%>
</div>

<p ng-show='isInvalidDate()'>Checkout Date Cannot be lesser than Checkin Date</p>

validationController.js

App.controller('validationController',['$scope', function($scope){
$scope.isInvalidDate = function(){
    return $scope.checkout.date < $scope.checkin.date;
}
}]) ;

App.js

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

Now when I select check out date lesser than checkin date, error is not displayed. Can someone please point me in right direction?

A controller only works on the DOM-element it is declared on and its children.

<p ng-show='isInvalidDate()'>Checkout Date Cannot be lesser than Checkin Date</p>

Is outside the scope of both your controllers.

Since you're trying to compare the value of both input s, you'd need to have both of them and the p holding your error message inside a single DOM element with the ng-controller attribute.

Also, the way you are using the ng-controller attributes seems to suggest you think of it as a singleton. It is not. In your case you have two instances of the controller , one of them knows about the checkin-date and the other one knows about the checkout-date. Neither of them would be able to actually perform the validaiton.

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