如果我的组件使用来自其他组件的数据(数据绑定),是否需要始终检查未定义的数据?
因为我一直希望数据能通过。如果没有,我应该让它崩溃,等待数据被修复,还是应该和平地检查和处理异常?
我想检查一下,但我想知道哪一个是最好的做法。
谢谢
发布于 2017-12-14 16:28:48
角将隐藏“未定义”的值,但是您可能想要使用ng斗篷来隐藏元素,直到角有机会处理任何指令(或者在某些情况下显式地使用ng-隐藏或ng-如果根据加载的内容有条件地隐藏/删除元素)。因此,在大多数情况下,答案是,不,不需要在绑定中检查它,但是是的,在加载数据或其他东西时,您必须决定视图的外观。
(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爸爸的标准是大多数人/地方的https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md事实上的标准
https://stackoverflow.com/questions/47824069
复制相似问题