Angular Form and Resource
HTML
<div ng:app>
<div ng:controller="UserForm">
<ul>
<li ng:cloak ng:repeat="record in allRecords">
<span ng:cloak ng:click="select(record)">{{record.name}}</span>
</li>
</ul>
<hr/>
<form name="myForm">
<input type="hidden" ng:model="form.id" />
<label>Name:</label><br/>
<input type="text" ng:model="form.name" required/> <br/><br/>
<button ng:click="cancel()" ng:disabled="{{isCancelDisabled()}}">Cancel</button>
<button ng:click="save()" ng:disabled="{{isSaveDisabled()}}">Save</button>
<button ng:click="clearForm()" >Clear Form (so you can Add a new person)</button>
</form>
<hr/>
Debug View:
<pre>form={{form}}
master={{master}}</pre>
</div>
</div>
CSS
.ng-invalid { border: 1px solid red; }
body { font-family: Arial,Helvetica,sans-serif; }
body, td, th { font-size: 14px; margin: 0; }
table { border-collapse: separate; border-spacing: 2px; display: table; margin-bottom: 0; margin-top: 0; -moz-box-sizing: border-box; text-indent: 0; }
a:link, a:visited, a:hover { color: #5D6DB6; text-decoration: none; }
.error { color: red; }
JavaScript
function UserForm() {
this.userResource = $resource('User/:userId', {userId:'@id'});
this.clearForm();
this.loadAll();
}
UserForm.prototype = {
clearForm: function () {
this.form = new this.userResource();
},
loadAll: function () {
this.allRecords = this.userResource.query();
},
loadOne: function (id) {
var self = this;
this.form = this.userResource.get({ userId: id }, function () {
self.master = angular.copy(self.form);
});
},
save: function() {
this.master = this.form;
self.form.$save(function (returnedInfo, responseHeaders) {
//self.loadAll(); // expensive way to refresh list (another server call), also causes a flicker
//figure out if we have to add to our list or update an existing list item
var i = self.arrayIndexOf(self.allRecords, function (obj) {
return obj.Id === returnedInfo.Id;
})
i > -1 ? self.allRecords[i] = returnedInfo : self.allRecords.push(returnedInfo);
this.cancel();
}
},
select: function (record) {
this.loadOne(record.id);
},
cancel: function() {
this.form = angular.copy(this.master);
},
isCancelDisabled: function() {
return angular.equals(this.master, this.form);
},
isSaveDisabled: function() {
return this.myForm.$invalid || angular.equals(this.master, this.form);
},
// general helper, should go elsewhere
arrayIndexOf: function (a, fnc) {
if (!fnc || typeof (fnc) != 'function') {
return -1;
}
if (!a || !a.length || a.length < 1) return -1;
for (var i = 0; i < a.length; i++) {
if (fnc(a[i])) return i;
}
return -1;
}
};