Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 557
mwhib Avatar asked Aug 30 '26 18:08

mwhib


2 Answers

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.

like image 132
AMG Avatar answered Sep 02 '26 07:09

AMG


yes like so:

<form name="vm.theFormName">

you can then access it via vm

like image 26
Joseph Le Brech Avatar answered Sep 02 '26 09:09

Joseph Le Brech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!