AngularJS,我应该经常检查未定义的边界值吗?

时间:2017-12-15 00:15:44

标签: angularjs validation exception undefined

如果我的组件使用其他组件的数据(数据绑定),是否有必要始终检查未定义?

因为我总是希望数据能够通过。如果它不应该让它崩溃并等待数据被修复,或者我应该检查并平安地处理异常?

我更喜欢检查,但我想知道哪种是最佳做法。

谢谢

1 个答案:

答案 0 :(得分:0)

Angular将隐藏“未定义”值,但您可能希望使用ng-cloak来使用CSS隐藏元素,直到angular有机会处理任何指令(或者在某些情况下明确使用ng-hide或ng) -if根据已加载的内容有条件地隐藏/删除元素。所以答案是在大多数情况下你不需要在绑定中检查它,但是你必须决定在加载数据或其他东西时视图的外观。

(function(){
  angular.module('myApp', [])
    .controller('MyCtrl', function($timeout){
      var ctrl = this;
      ctrl.model = {
        testA: 12,
        testB: undefined
      }
      
      $timeout(function(){
        ctrl.model.testB = "something here now"
      }, 5000)
      
    })
})();
pre{
background:yellow;
}

/*
Guarantees the elements aren't shown if they have ng-cloak
attribute, angular will remove this once it has processed the
directives on the element, at this point ng-if can take over
conditionally removing/adding the element or ng-hide can conditionally
remove it from display with css*/
[ng-cloak]{
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>


<div ng-app="myApp" ng-controller="MyCtrl as ctrl">
  <div>
    {{ctrl.model.testA}} <span ng-if="ctrl.model.testB" ng-cloak>-</span> {{ctrl.model.testB}}
  </div>
  
  <pre>{{ctrl|json}}</pre>
</div>

对于一般的最佳实践,只搜索有角度的最佳实践(或风格指南),但有一些,但John Papa是大多数人/地方的事实标准https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md