首页 > 解决方案 > Angular:仅在异步检索数据时如何运行函数?

问题描述

我有两个文件:

index.html:我想在其中使用自定义指令

<body>   
    <div ng-controller="friendsController">
        <random-friend friends="friends" title="'Random Friend'"></random-friend>
    </div>
</body>

app.js:其中包含:

代码:

// 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()仅在检索到朋友数组时才运行该函数?

标签: angularjs

解决方案


您可以使用 ng-if 处理此问题

 <div ng-controller="friendsController">
  <div ng-if="friends.length > 0">
        <random-friend friends="friends" title="'Random Friend'"></random-friend>
  </div>
 </div>

推荐阅读