在 angular 中处理一系列警报

handling an array of alerts in angular

好的,所以我正在尝试自学 angular 但我被困在我想完成的事情上。基本上,它是一个使用 UI Bootstrap 构建的简单表单。我希望在用户将焦点放在文本框、文本区域、单选按钮组等时显示一个信息警报框。并且此类警报框将包含有关他们正在填写的特定字段的说明。每当用户点击关闭时,警告框就应该消失。到目前为止,我已经有了与 onFocus 和 onBlur 一起使用的功能。我的问题是,我无法隔离仅适用于用户所在领域的功能。除非我在我的应用程序中创建多个控制器,否则我很难相信这会是解决方案。

如何在数组中声明多个警告框并从各自的输入字段中调用它们?

这是我的app.j代码

var nameApp = angular.module('nameApp', ['ngAnimate', 'ui.bootstrap', '$strap.directives']);

nameApp.controller('InstructionsCtrl', function ($scope, $sce, $timeout) {

    $scope.alerts = [];

    $scope.addAlert = function () {
        $scope.alerts.push({ type: 'info', msg: 'Please input your first name' });
    };

    $scope.closeAlert = function (index) {
        $scope.alerts.splice($scope.alerts.indexOf(this), 1);
    };

});

我包括一个 PLUNKER here

提前致谢

我建议将其简化为仅模板,因为根据描述的要求,您不需要显示与每个输入相关的多个警报。

在下面的警报中有一个 ng-show 并且每个输入设置焦点和模糊的值。

<div class="form-with-instructions" ng-controller="InstructionsCtrl" novalidate="novalidate">
    <div role="form">
        <div class="row">
            <div class="col-md-6 col-sm-6 col-xs-12">
                <div class="form-group">
                    <label>First Name </label>
                    <input type="text" value="" class="form-control" ng-focus="fnAlert = true" ng-blur="fnAlert = false"/>
                </div>
            </div>
            <div class="col-md-6 col-sm-6 col-xs-12">
              <div class="alert alert-warning alert-dismissible" role="alert" ng-show="fnAlert">
                <button type="button" class="close" ng-click="fnAlert = false"><span aria-hidden="true">&times;</span></button>
                Please input your first name
              </div>
            </div>
        </div> 
        <div class="row">   
            <div class="col-md-6 col-sm-6 col-xs-12">
                <div class="form-group">
                    <label>Last Name </label>
                    <input type="text" value="" class="form-control" ng-focus="lnAlert = true" ng-blur="lnAlert = false"/>
                </div>
            </div>
            <div class="col-md-6 col-sm-6 col-xs-12">
              <div class="alert alert-warning alert-dismissible" role="alert" ng-show="lnAlert">
                <button type="button" class="close" ng-click="lnAlert = false"><span aria-hidden="true">&times;</span></button>
                Please input your first name
              </div>
            </div>
        </div>            
    </div>  
</div>

如果您确实想使用警报数组方法,那么您需要为每个输入定义不同的警报数组。