Reputation: 5485
<form novalidate>
<label>Name</label>
<input type="text" name="name" ng-model="newcontact.name" required/>
<label>Email</label>
<input type="text" name="email" ng-model="newcontact.email" required/>
<label>Phone</label>
<input type="text" name="phone" ng-model="newcontact.phone" required/>
<br/>
<input type="hidden" ng-model="newcontact.id" />
<input type="button" ng-if="newcontact.id" value="UPDATE" ng-click="saveContact()" />
<input type="button" ng-if="!newcontact.id" value="SAVE" ng-click="updateContact()" />
</form>
Consider the above form, In this create/edit is using the same template, So i like to show Button names as 'UPDATE' or 'SAVE' based on newcontact.id value.
Need to concentrate only on these :
<input type="button" ng-if="newcontact.id" value="UPDATE" ng-click="saveContact()" />
<input type="button" ng-if="!newcontact.id" value="SAVE" ng-click="updateContact()" />
Since angular do not have ng-else, so how to achieve this.
Also need to know. 2. how you secure business logic from user in AngularJS
Upvotes: 0
Views: 8465
Reputation: 3366
Well,
you can just make use of ng-show
here, by using a button instead:
<button ng-click="save()">
<span ng-show="newcontact.id">Update</span>
<span ng-show="!newcontact.id">Save</span>
</button>
with a save function that reacts to the state of newcontact.id
:
angular.module('my.module').controller(['$scope', function($scope) {
$scope.save = function() {
if(typeof scope.newcontact.id === 'undefined') {
// save
} else {
// update
}
}
}]);
EDIT: Another option could be not to decide once whether or not it's a new contact:
angular.module('my.module').controller(['$scope', function($scope) {
$scope.newcontact = {};
$scope.save = function() {
/** Your save function */
}
// with a set contact, this will now always evaluate to 'Save'
$scope.label = !!scope.newcontact.id ? 'Update' : 'Save';
// so we go for something different:
$scope.$watch('newcontact', function(newValue) {
//this watches the newcontact for a change, 'newValue' is the new state of the scope property
$scope.label = !!newValue.id ? 'Update' : 'Save';
});
}]);
Note: That is just a crude example, you should probably use a service in conjunction with an API to save your users. what the example does is basically watching a scope property and changing the label accordingly. See here for a more detailed description.
and then use it in the form:
<button ng-click="save()">{{label}}</button>
EDIT 2: To answer your question about hiding business logic from the user - you simply cannot. AngularJS is a JavaScript Framework and you give a users browser the full code to run your application. If you really have sensitive logic, put it on the server side and expose an interface to it (e.g. via JSON API).
Upvotes: 4