首先,看看下面的示例代码。
// parent-controller.js
export default function parentCtrl($scope, MyService) {
function init() {
MyService.get().$promise.then(data => $scope.data = data);
}
}
// child-controller.js
export default function childCtrl($scope) {
const MY_LIST = ['a', 'b', 'd'];
function getFoo() {
if ($scope.data) {
return MY_LIST.find((el) => el === $scope.data.foo);
}
}
function getBar() {
if ($scope.data) {
return MY_LIST.find((el) => el === $scope.data.bar);
}
}
}
// my.html
~(snipped)~
<span>{{ getBar() }}</span>
~(snipped)~
当我需要检查是否加载$scope.data
时,我会按上述方式执行操作。但它似乎不是一个很好的代码:/
你有什么想法吗?
感谢。
编辑:为什么我需要检查一下?因为从HTML中的嵌入代码调用getBar()
时不会发生未定义的错误。我想运行此代码而没有使用if ($scope.data) { ~ }
的未定义错误。
编辑:毕竟,我使用ng-if
解决了这个问题,如下所示。
<div ng-if="data">
<span>{{ getBar() }}</span>
</div>