Search code examples
angularjsvalidationtypescriptangularjs-scope

How do I access angular's $scope.{{formName}}.$dirty boolean with TypeScript?


I have a form with a name attribute, and I'm trying to use angular's $scope variable to access the form, and its $dirty boolean.

The problem is I'm using TypeScript, and if I set the type for a $scope variable to one of the interfaces ng.IScope or ng.IFormController from DefinitelyTyped's typings file, I can't type in something like

$scope.myFormINeedToAccess.$dirty

because everything is strongly typed, and if I do I get the error,

Property 'myFormINeedToAccess' does not exist on type 'IScope'.

or

Property 'myFormINeedToAccess' does not exist on type 'IFormController'.

Because I was introduced to AngularJS, and TS at the same time, I've not written any angular in javascript, but from what I think I understand the $scope variable (if variable is the right word for it) is accessible globally. So anywhere you want in any level of encapsulation you can just drop

$scope.(tons of options/stuff in the current view).(a bunch of additional options)

But I'm feeling very restricted by only being able to say

$scope.(15ish options defined by ng.IScope or ng.IFormController)

What can I do to use $scope: ng.IScope or $scope: ng.IFormController in such a way that I can successfully access the $dirty boolean via the statement,

$scope.myFormINeedToAccess.$dirty


Solution

  • 1) Don't use $scope with Typescript - use controller as syntax.
    2) Create a public variable of type ng.IFormController in your controller.
    3) Set the name of your form to the variable created in #2.

    HTML:

    <div ng-controller="MyController as vm">
        <form name="vm.myForm">
            // form elements here
        </form>
    </div>
    

    Controller:

    export class MyController() {
        public myForm: ng.IFormController;
    
        public someFunction(): void {
            if(this.myForm.$dirty) {
                // do something
            }
        }
    }
    

    I've obviously left out quite a bit of the plumbing code, but this should give you the general gist.