<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>
考虑上面的表单,在这个创建/编辑中使用相同的模板,所以我喜欢显示 根据 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()" />
既然Angular没有ng-else,那么如何实现呢?
还需要知道。 2. 如何在 AngularJS 中保护用户的业务逻辑
最佳答案
嗯,
您可以在这里使用ng-show
,通过使用按钮来代替:
<button ng-click="save()">
<span ng-show="newcontact.id">Update</span>
<span ng-show="!newcontact.id">Save</span>
</button>
具有对 newcontact.id
的状态使用react的保存函数:
angular.module('my.module').controller(['$scope', function($scope) {
$scope.save = function() {
if(typeof scope.newcontact.id === 'undefined') {
// save
} else {
// update
}
}
}]);
编辑:另一种选择可能是不一次决定是否是新联系人:
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';
});
}]);
注意:这只是一个粗略的示例,您可能应该将服务与 API 结合使用来拯救您的用户。该示例的作用基本上是监视范围属性并相应地更改标签。请参阅here以获得更详细的描述。
然后以以下形式使用它:
<button ng-click="save()">{{label}}</button>
编辑2:要回答有关向用户隐藏业务逻辑的问题-您根本做不到。 AngularJS 是一个 JavaScript 框架,您可以向用户浏览器提供运行应用程序的完整代码。如果您确实有敏感逻辑,请将其放在服务器端并向其公开接口(interface)(例如通过 JSON API)。
关于javascript - AngularJS 条件 ng-if 显示保存和更新按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22165184/