angularjs - Angular:仅在异步检索数据时如何运行函数?
问题描述
我有两个文件:
index.html:我想在其中使用自定义指令:
<body>
<div ng-controller="friendsController">
<random-friend friends="friends" title="'Random Friend'"></random-friend>
</div>
</body>
app.js:其中包含:
- 控制器:具有异步
$scope.friends
分配其值,并将在自定义指令中使用。 - 每次页面加载时输出随机朋友(元素)的自定义指令。
代码:
// Module
const myApp = angular.module('myApp', []);
// Custom Directive
myApp.directive('randomFriend', [function() {
return {
restrict: 'E',
scope: {
friends: '=',
title: '='
},
template: `<h4>{{friends[randomIndex]}}</h4>`,
controller: function generateRandomNumber($scope) {
$scope.randomIndex = Math.floor(Math.random() * $scope.friends.length); // TypeError: Cannot read property 'length' of undefined
}
};
}]);
// Controller
myApp.controller('friendsController', ['$scope', $scope => {
$http.get('data/friends.json').then(function(response) {
$scope.friends = response.data;
});
}]);
问题是当代码到达时$scope.friends.length
,控制台返回错误“TypeError:无法读取未定义的属性'长度'”,因为尚未检索到请求数据。
那么,如何generateRandomNumber()
仅在检索到朋友数组时才运行该函数?
解决方案
您可以使用 ng-if 处理此问题
<div ng-controller="friendsController">
<div ng-if="friends.length > 0">
<random-friend friends="friends" title="'Random Friend'"></random-friend>
</div>
</div>
推荐阅读
- nsis - 如何使用 NSIS 使用 Visual Studio 生成的文件生成安装程序
- jquery - 使 div 向上显示,同时上下推动兄弟 div
- properties - OWL中对象属性hasTopping在不同上下文中的特征定义
- c - C 程序中的意外结果,使用 Malloc 和 for 循环
- sql - SQL Server - 从分层表中获取根节点
- php - 不能做作曲家更新 5.7
- javascript - 由于 div 样式,Google 地图在弹出窗口中不可见
- react-native-android - 反应原生 sqlite 存储不为 android 返回任何内容
- c# - Int32.Parse 与 Int32.TryParse
- oauth-2.0 - 谷歌登录卡在 oauth2/iframe