如果错误返回角度js,则将类添加到div

时间:2017-02-15 10:31:27

标签: angularjs

代码工作正常,并通过API(http.get)获取数据, 如果有错误的条目,则返回401错误, 如何将类“错误”添加到div,

<form name="form" ng-submit="vm.frmmn()">
  <div class="form-group" ng-class="?">
    <label>Tile</label>
    <input type="text" class="form-control col-md-1" placeholder="001">
    <input type="text" class="form-control" placeholder="02">
    <span class="help-block" ng-if="error">Error : {{error}}</span>
  </div>
  <div class="text-center">
    <button type="submit" class="btn btn-primary">
      Search Mobile Network
    </button>
  </div>
</form>

JS

 function frmmn() {

   var path_mn = api + "operator/" + vm.mcc + "/" + vm.mnc;
   $http({
     method: 'GET',
     url: path_mn,
     headers: {
       'Authorization': 'Bearer ' + bearer.token
     }
   }).then(function(resp) {
     $scope.itemsm = resp.data;
   }).catch(function(err) {
     if (err.status === 404) {
       $scope.error = "error : " + err.status
     };
   });
 }

3 个答案:

答案 0 :(得分:2)

您可以使用ng-class

<div ng-class="{ 
       'error': error condition here
}"></div>

'error'是类,并将条件放在它旁边。

答案 1 :(得分:2)

除上述答案外,重置$scope.error开始$http以隐藏错误消息&#39;重试&#39;。使用$scope.error = undefined

frmmn功能的更改:

function frmmn(){
    var path_mn = api + "operator/" + vm.mcc + "/" + vm.mnc;
    $scope.error = undefined;
    $http({
        method:'GET',
        url: path_mn,
        headers: {'Authorization':'Bearer '+bearer.token}
        }).then(function(resp){
            $scope.itemsm=resp.data;
        }).catch(function (err) {
            if(err.status === 404){
                $scope.error = "error : " + err.status 
            };
    });
}

答案 2 :(得分:2)

使用ng-class内置指令Here是一个很好的示例,说明如何使用ng-class

示例

    function frmmn(){
        var path_mn = api + "operator/" + vm.mcc + "/" + vm.mnc;
        $scope.status = {
            error_404 : false; //define a boolean variable
        }
        $http({
            method:'GET',
            url: path_mn,
            headers: {'Authorization':'Bearer '+bearer.token}
            }).then(function(resp){
                $scope.itemsm=resp.data;
            }).catch(function (err) {
                if(err.status === 404){
                    $scope.error = "error : " + err.status 
                    $scope.status.error_404 = true; // set errorStatus to true
                };
        });
    }

<强> HTML

<span class="help-block" ng-class="{'error':status.error_404 }" here ng-if="error" >Error : {{error}}</span>

CSS

 .error{
       color:red;
    }