mwhib
mwhib

Reputation: 113

How to reference a form from controller

Background: I have an AngularJs wizard like app with 3 steps. The wizard steps contain 4 uiRouter states that share a single controller. The first state is an abstract view containing bootstrap pill navigation with a ui-view as a placeholder for the other 3 nested states. The 3 nested states have a separate views that contain uniquely named forms. I would like to control the pill navigation in the the parent state by checking if the current visible form is valid; if the form is invalid then I would hide/disable the ability for the user to click on the next navigation pill.

Note: I'm using the "controller as" syntax declared in the uiRouter states.

Issue: I don't seem to be able to get a reference to the current viewable form from within the controller.

Here's what I've tried: 1. passing in the reference to the form visible form in an init call --> gets undefined error when I try to write to console 2. renaming the forms and even passing in the scope reference as described in this link: http://www.technofattie.com/2014/07/01/using-angular-forms-with-controller-as-syntax.html

Demo: Here's a plnkr link that shows intent: http://plnkr.co/edit/YUnwoBD2dt4bzbfujJSW

Controller code:

(function () {
    'use strict';

    angular
        .module('recquisitionManagement')
        .controller('RecquisitionEditCtrl', [RecquisitionEditCtrl]);

    function RecquisitionEditCtrl() {

        var vm = this;

        //  get ref to request form
        vm.setRequestForm = function(form) {
            vm.requestForm = form;
            console.log(form);

            // tried to call from form ng-init --> undefined response
        }

        //  console.log($scope.vm.requestForm);
        //  console.log(vm.requestForm);

        vm.recquisition = { id: 0, name: 'some name', date: 'date here' };
        vm.requestFormIsInvalid = true;    //this.requestForm.$valid;
        vm.approvalFormIsInvalid = true;


        if (vm.recquisition && vm.recquisition.id > 0) {
            vm.title = 'Edit';
        } else {
            vm.title = 'Create';
        }
    }
}());

Any suggestions on how to get the needed form reference?

Upvotes: 3

Views: 3212

Answers (3)

Joseph Le Brech
Joseph Le Brech

Reputation: 6653

yes like so:

<form name="vm.theFormName">

you can then access it via vm

Upvotes: 1

Frank Martin
Frank Martin

Reputation: 1841

Bit late now I realise but you were passing the ctrl as an array, needed to change this:

.controller('RecquisitionEditCtrl', [RecquisitionEditCtrl]);

to this:

.controller('RecquisitionEditCtrl', RecquisitionEditCtrl);

Upvotes: 0

AMG
AMG

Reputation: 704

Multiple options are explained here: Can I access a form in the controller?

Also it can be good to rename functions that share the name of the controller and try to use the common angular practice.

Upvotes: 1

Related Questions