tamasgobesz tamasgobesz - 4 months ago 134x
Javascript Question

AngularJS/Angular Material form validity with md-select

I'm using AngularJS and Angular Material for a web app I'm building, and I have the following HTML form in a dialog window:

<form name="cdc.clientForm">
<md-dialog class="userDialog" ng-init="cdc.init()">
<md-input-container flex>
<label>Company name</label>
<md-select ng-model="cdc.client.companyName" required>
<md-option value="Company 1">Company 1</md-option>
<md-option value="Company 2">Company 2</md-option>
<label>Client name</label>
<input type="text" ng-model="cdc.client.name" required>
<md-button ng-click="cdc.submit()" ng-disabled="cdc.clientForm.$invalid">OK</md-button>
<md-button ng-click="cdc.cancel()">Cancel</md-button>

And I have the following controller behind it:

(function () {
'use strict';
.controller('ClientDialogController', ClientDialogController);

ClientDialogController.$inject = ['$mdDialog', 'client'];

function ClientDialogController($mdDialog, $q, client) {
var vm = this;
vm.init = init;
vm.submit = submit;
vm.cancel = cancel;

function init() {
if ((client !== undefined) && (client !== null)) {
vm.client = client;

function cancel() {

function submit() {

I'm reusing the dialog form for both the creation and update of my model.

My problem lies basically with the form validity when I want to edit the object.

If I have a md-select in the form, and the md-select is required and it's pristine, as in, the user doesn't modify the select value, then the form is considered invalid. Removing the select, only with text inputs with a bound model, I don't have the issue, the forms is considered valid.

How could I fix this issue, what would be a recommended way to deal with this?


Well, I figured this out on my own, maybe it will help somebody else.

The key to this was already in the docs under the "Selects and object equality" part, I just didn't notice it, as it's not that obvious.

The problem lies with the way Javascript check for equality, if I add the ng-model-options directive as below, the form is set to be valid:

<md-select ng-model="cdc.client.companyName" required ng-model-options="{trackBy: '$value'}">
    <md-option value="Company 1">Company 1</md-option>
    <md-option value="Company 2">Company 2</md-option>