Skip to content
This repository has been archived by the owner on Jul 1, 2020. It is now read-only.

ControllerAs Syntax

Ghislain B edited this page Mar 23, 2017 · 16 revisions

Since version 1.3.36

The library now also support the ControllerAs syntax, so there is no need to specify the $scope anymore, however you will need use the ValidationService to specify the ControllerAs inside the Angular-Validation global options. It is very important that you declare and set your global validation options before any function declaration else it will fail. For more details on the other available global options, please refer to the Wiki - Global Options

From the Live Plunker Demo you can see the ControllerAs in action on the 2 Forms page (just click on the type "2 Forms")

Directive/Service

// inject the ValidationService inside your Controller
myApp.controller('Ctrl', function ($scope, ValidationService) {
  var vm = this;

  // declare the Angular-Validation global options BEFORE the functions declaration
  var vs = new ValidationService({ controllerAs: vm });

  // OR you could also do it in 2 lines
  var vs = new ValidationService();
  vs.setGlobalOptions({ controllerAs: vm });

  // then after, you can declare your functions
  vm.submit = function () {
     // and use the vs Service object previously created outside of this function
     if(vs.checkFormValidity(vm.myform)) {
	      // proceed with submit
     }
});

This would FAIL

The following code would fail because the Directive already processed the validation before reaching your function and getting the controllerAs is already too late.

// inject the ValidationService inside your Controller
myApp.controller('Ctrl', function ($scope, ValidationService) {
  var vm = this;

  // then after, you can declare your functions
  vm.submit = function () {
     // and use the myValidation Service object previously created outside of this function
     vs.checkFormValidity(vm.myform);

     // calling the controllerAs here would would FAIL, it's too late in the process
     new ValidationService({ controllerAs: vm }).checkFormValidity(vm.myform);
  }
});
Clone this wiki locally