如何使指令不那么冗长

How to make the directives less verbose?

本文关键字:何使 指令      更新时间:2023-09-26

这里有一个登录字段、一个密码、用户名和登录按钮。正如你所看到的,它非常冗长。

<form name='form' novalidate ng-submit="form.$valid && submit('/login')" ng-focus="showError=false" ng-controller='loginController' >
    <h2>Login</h2>
    <div class="form-group has-feedback" ng-class="{ 'has-error' : ((form.username.$touched || form.$submitted) && form.username.$invalid) || showError}">
        <input ng-focus="showError=false" type="email" name="username" class="form-control" placeholder="Email" ng-model='data.username' ng-disabled="loading" required>
        <span ng-show="((form.username.$touched || form.$submitted)  && form.username.$invalid) || showError" class="glyphicon form-control-feedback glyphicon-remove"></span>
        <p ng-show="(form.username.$touched || form.$submitted)  && form.username.$invalid" class="help-block text-left">Enter a valid email</p> 
    </div>
    <div class="form-group has-feedback" ng-class="{ 'has-error' : ((form.password.$touched || form.$submitted)  && form.password.$invalid) || showError}">
        <input ng-focus="showError=false" type="password" name="password" class="form-control" placeholder="Password" ng-model='data.password' ng-disabled="loading" required>
        <span ng-show="( (form.password.$touched || form.$submitted)  && form.password.$invalid ) || showError" class="glyphicon form-control-feedback glyphicon-remove"></span>
        <p ng-show="(form.password.$touched || form.$submitted)  && form.password.$invalid" class="help-block text-left">Enter a password</p> 
    </div>
    <button type="submit" class="btn btn-primary btn-block" ng-disabled="loading">
     Log in</button>
</form>

我反复使用的表达式

((form.username.$touched || form.$submitted)  && form.username.$invalid) || showError

在这个例子中,有没有一种聪明的方法来减少代码量?有什么最佳实践吗?

首先,您有自己的控制器来处理模板中的大部分逻辑。在那里,您似乎声明了类似$scope.login = function(){ ... }的东西,它是在您进行表单验证后调用的。(只是猜测)。

代替这种方法,我会尝试使用$scope.processForm = function(){ .. }之类的东西,它在提交按钮上被调用。然后,这个函数应该调用一个validate()函数来完成验证工作,如果成功,就会调用login()函数。

下一步是实现service,例如验证服务,它不仅可以由登录控制器使用,而且可以由所有关心验证的控制器使用(仅作为示例)。

这将去掉所有的布尔表达式,并且通常会得到更干净、更好的可维护代码。

我不确定最佳实践,但您可以始终在作用域上放置一个函数并调用它。因此,在控制器中:

scope.showMessage = function (inputName) {
    return ((form.username.$touched || form.$submitted)  && form[inputName].$invalid) || showError;
}

然后从标记中调用,例如:

<div class="form-group has-feedback" ng-class="{ 'has-error' : showMessage('username')">