【问题标题】:Angular loading feedback on button click按钮单击时的角度加载反馈
【发布时间】:2014-09-11 15:58:23
【问题描述】:

在使用 Angular 在实时服务器上测试项目时,我注意到在用户提交表单和实际发生的任何事情之间存在一个小的延迟(当涉及后端进程和数据库时)。所以我想创建视觉反馈,点击按钮变成加载 gif 或其他东西。

我不知道如何通过我的 Angular 提交函数访问按钮元素。

假设我有这个 HTML:

<form ng-submit="submit(user)">
  <input type="text" ng-model="user.name" />
  <button type="submit">Submit</button>
</form>

然后在 Angular 中:

$scope.submit = function(user){
  //http requests and whatever else to process the form.
  //how can I access the button element to alter it's visual state?
});

我只是不知道如何访问单击的按钮。理想情况下,我不想使用特定的 id 或类,因为我想将其应用于所有单击的按钮。

我已经知道如何创建我想要的视觉样式,只是将它应用到相关的元素上是个问题。

【问题讨论】:

    标签: javascript html angularjs


    【解决方案1】:

    只需使用范围变量更改 ng-style 或 ng-class(首选):

    使用 ng-style 的简单样式:

    HTML

    <form ng-submit="submit(user)">
      <input type="text" ng-model="user.name" />
      <button type="submit" ng-style="{'opacity': buttonOpacity} ">Submit</button>
    </form>
    

    JS:

    $scope.buttonOpacity = 0.4;
    $scope.submit = function(user){
      //http requests and whatever else to process the form.
      //how can I access the button element to alter it's visual state?
      $scope.buttonOpacity = 0.4;
    });
    

    使用 ng-class 的更好选择:

    HTML

    <form ng-submit="submit(user)">
      <input type="text" ng-model="user.name" />
      <button type="submit" ng-class="{'myAlteredButtonClass': applyNewButtonClass === true} ">Submit</button>
    </form>
    

    JS:

    $scope.applyNewButtonClass = false;
    $scope.submit = function(user){
      //http requests and whatever else to process the form.
      //how can I access the button element to alter it's visual state?
      $scope.applyNewButtonClass = true;
    });
    

    CSS:

    .myAlteredButtonClass {
        opacity: 1;
        border: 1px solid;
        color: green;
        ... etc.
    }
    

    【讨论】:

    • 啊,是的,ng-class 方法似乎是一个相当合乎逻辑的解决方案。我会用的,谢谢。
    【解决方案2】:

    在 Angular 中有很多方法可以做到这一点。其中有ng-show和ng-if。使用 ng-show,您可以执行以下操作:

    <form ng-submit="submit(user)">
      <input type="text" ng-model="user.name" />
      <button ng-show="!submitted" type="submit">Submit</button>
      <div ng-show="submitted" >Loading spinner here</div>
    </form>
    

    和

    $scope.submit = function(user){
      $scope.submitted = true;
    });
    

    【讨论】:

    • 如果您想显示加载微调器,这是一个很好的简单解决方案。
    • 谢谢,这是一个解决方案,但就我而言,我想更改按钮而不是引入新元素。
    【解决方案3】:

    【讨论】:

    • 这不是在 Angular 中更改视图的正确方法,这将使用类似 jQuery 的方法来访问元素。要从控制器更改视图,正确的方法是使用 ng-class(首选)或可能的 ng-style
    • 问题的提出条件是:理想情况下,我不想使用特定的 id 或类。此外,您所说的 jquery 样式是 Angular 文档的一部分。
    猜你喜欢
    • 2020-03-13
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2019-03-27
    • 1970-01-01
    相关资源
    最近更新 更多