dagda1 dagda1 - 3 months ago 17
AngularJS Question

reference form in angular component without scope

Currently I have this component definition:

var controller = ['$http', '$timeout', '$scope', function($http, $timeout, $scope) {
this.isInvalid = function() {
return $scope.changePinForm.$invalid;
};
}];

var component = {
templateUrl: path.fromRoot('/application/libs/components/pin-change/view/pin-change.html'),
controller: controller,
controllerAs: 'vm'
};

angular.module('pin-change', ['confirm-reject', 'compare-validator', 'is-numeric'])
.component('pinChange', component);
});


Which references this html file via
templateUrl
:

<form name="changePinForm" class="form-horizontal">
<!-- etc. etc. -->
</form>


At the moment I am having to use scope to reference the form:

$scope.changePinForm.$invalid;


I would prefer to avoid scope and reference the form from the component's controller.

Is this possible or is scope still the only way?

Answer

You could make your form name to be name="vm.changePinForm" use vm(controller alias).

And then you can easily access vm.changePinForm.$invalid inside your controller. By which you aren't depending on $scope inside your controller.

var controller = ['$http', '$timeout', 
  function($http, $timeout) {
    var vm = this;
    vm.isInvalid = function() {
        return vm.changePinForm.$invalid;
    };      
  }
];