Reputation: 9559
I have an angular form where the questions are specified in an array.
The HTML is as follows:
<form ng-controller="SupplierController" name="newSupplierForm">
<p>Enter details for the new Supplier. The new supplier will be added to category {{selectedCategory.description}}</p>
<p ng-repeat="field in formfields">
<label class="field" for="{{field.name}}" ng-hide="newSupplierForm.{{field.name}}.$dirty && (newSupplierForm.{{field.name}}.$error.required || newSupplierForm.{{field.name}}.$invalid)">{{field.caption}}</label>
<label class="error" for="{{field.name}}" ng-show="newSupplierForm.{{field.name}}.$dirty && (newSupplierForm.{{field.name}}.$error.required || newSupplierForm.{{field.name}}.$invalid)">{{field.caption}}</label>
<input type="{{field.type}}" name="{{field.name}}" ng-model="newSupplier[field.name]" ng-required="{{field.required}}">
</p>
<button ng-disabled="newSupplierForm.$invalid" ng-click="saveSupplier()">Save</button>
</form>
The Controller is:
financeApp.controller('SupplierController', function($scope, $http) {
$scope.formfields = [
{caption:'Name :', name:'name', required:"true", type:"text"},
{caption:'Address :', name:'address1', required:"true", type:"text"},
{caption:' :', name:'address2', required:"true", type:"text"},
{caption:' :', name:'address3', required:"", type:"text"},
{caption:' :', name:'address4', required:"", type:"text"},
{caption:'Post Code :', name:'postcode', required:"", type:"text"},
{caption:'Email :', name:'email', required:"", type:"email"},
{caption:'Phone :', name:'phone', required:"", type:"text"}
];
$scope.newSupplier = {};
$scope.saveSupplier = function() {
$http.post('/finance/supplier', newSupplier).success(function(data) {
alert(data);
});
}
});
It all appears to work correctly, except that the Save button is never enabled, even if the form is valid. The research I've done so far would indicate that this should work, but it does not.
Example : Disable a button if at least one input field is empty using ngDisabled
What am I doing wrong?
Also, is there any way of improving this code generally? This is my first attempt at Angular.
Upvotes: 0
Views: 1552
Reputation: 1816
Try ng-required="field.required"
, without the curly braces, as this already expects an angular expression.
And inside the controller, treat the required
as true or false, not as a string.
As for how to improve this, the approach you used is ok, but if your form will always have the same fields (it's not dynamic), you should create html elements for each field, and not declare them inside the controller.
The controller should control the behaviour of the view, not what fields to display (in a non dynamic point of view).
Upvotes: 1