Reputation: 1387
I have created tab controls and each tab is using different controller. Each tab has some input types and also it has got validations. I have used form for each tabs and different controller for each tabs. I want to validate the form when i click on another tab. For example if there is any invalid value in Tab 1 then when user clicks on Tab 2 it should validate Tab 1 and if any invalid value is found then it should focus the invalid field and do not allow to switch tabs. Switching of tabs should be allowed only when form in the tab is valid.
Now i am not able to check whether form is valid or not during tab switch because tab DOM is out side the form and its controller. So i cant access formname.$valid
property. So how i can handle this scenario?
Here is sample plunker
Upvotes: 1
Views: 2420
Reputation: 3733
In plunker example, you have used different form for different template and included using ng-include
. Instead you can make only one form and in individual template add only required form element
instead of individual form. Use form validation on click event of specific tab and check whether input is valid or not. If input is not valid show error message and prevent switching from current tab to next tab.
Notes: Don't use ng-if
for showing or hiding template instead use ng-show
or ng-hide
Upvotes: 1
Reputation: 1303
You can do this:
Step1: Inject the $rootScope service in the controllers.
Step2: Now make a $rootScope variable say $rootScope.validForm=false;
Step3: Now you can set/check in every controller
if(formname.$valid){
//Your code
$rootScope.validForm=true;
}else{
$rootScope.validForm=false;
}
Step4: set ng-disable="$root.validForm===false" in the html
You can play with this rootScoep variable to maipulate accordingly. More over your structure is not correct make one form , also use ng-repeat for tab generation, need lot of improvements in your code.
Upvotes: 0
Reputation: 87
while click on the second tab from second controller call controller of first tab and check form data is set or not.if not set call ng-click function of first tab. we can communicate between two controllers using following ways\ 1)sharing a data service
function FirstController(someDataService)
{
// use the data service, bind to template...
// or call methods on someDataService to send a request to server
}
function SecondController(someDataService)
{
// has a reference to the same instance of the service
// so if the service updates state for example, this controller knows about it
}
2)emit event on the scope
function FirstController($scope)
{
$scope.$on('someEvent', function(event, args) {});
// another controller or even directive
}
function SecondController($scope)
{
$scope.$emit('someEvent', args);
}
Upvotes: 0