显示成功/失败消息,而不在AngularJS中引用ID

Rac*_*elD 6 angularjs

我正在使用AngularJS创建一个简单的表单来向数据库添加新记录.所以我在控制器中通过ajax提交表单,并成功添加了一条新记录.

我的问题是,向用户展示成功确认的Angular方式是什么.如果这是vanilla JS,我只会隐藏表单,同时会显示以前隐藏的成功消息.然后在几秒钟后淡出消息并将表单重新输入.

在Angular有更好的方法吗?除了$('形式#myForm').hide()和$('div#successMessage').show()?

ajk*_*ajk 8

您可以使用ngShow指令来完成此任务.例如,如果您在成功提交后设置$scope.submissionSuccesstrue,则可以在模板中添加以下内容:

<div ng-show="submissionSuccess">It worked!</div>
Run Code Online (Sandbox Code Playgroud)


Max*_*tin 2

在 Angular 中是否有更好的方法来做到这一点?除了 $('form#myForm').hide() 和 $('div#successMessage').show() 之外?

是的,您可以使用ng-showng-hide

假设您有某种方法getRunningState()可以根据某种状态返回 1 到 4 之间的整数。所以我们可以这样写:

 <span ng-show="getRunningState() == 1">Running...</span>
 <span ng-show="getRunningState() == 2">Paused</span>
 <span ng-show="getRunningState() == 3">Stopped</span>
 <span ng-show="getRunningState() == 4">Finished!</span>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,只会显示 4 个选项中的一个

作为旁注

如果您有兴趣将成功/失败放入对话框中(在我看来似乎相当不错),这里是基于以下示例:

  • Bootstrap的CSS
  • ui引导程序

在此输入图像描述

function DialogDemoCtrl($scope, $dialog, $http){

  // Inlined template for demo
  var t = 
          '<div class="modal-body">'+
          '<div class="alert alert-success" ng-show="true">'+
'   <button type="button" class="close" data-ng-click="close(result)" >x</button>'+
'   <strong>Done!</strong> {{successTextAlert}}'+
' </div></div>';

     $scope.successTextAlert = "Some content";
     $scope.showSuccessAlert = true;     


  $scope.opts = {
    backdrop: true,
    keyboard: true,
    backdropClick: true,
    template:  t, // OR: templateUrl: 'path/to/view.html',
    controller: 'TestDialogController',
    resolve: {}
  };

  $scope.openDialog = function(){

    $scope.opts.resolve.successTextAlert = function() {
            return angular.copy($scope.successTextAlert);
        }

         $scope.opts.resolve.showSuccessAlert = function() {
            return angular.copy($scope.showSuccessAlert);
        }

    var d = $dialog.dialog($scope.opts);
    d.open().then(function(result){
      if(result)
      {
        alert('dialog closed with result: ' + result);
      }
      else{
        alert('dialog closed');
      }
    });
  };

}
Run Code Online (Sandbox Code Playgroud)

就我而言,我显示“成功”(引导程序)

演示Plunker

您可以通过仅更改一行来更改对话框类型/颜色:

<div class="alert alert-success">...</div>
<div class="alert alert-info">...</div>
<div class="alert alert-warning">...</div>
<div class="alert alert-danger">...</div>
Run Code Online (Sandbox Code Playgroud)