【发布时间】:2020-09-10 20:39:09
【问题描述】:
我正在使用这个 app.js 文件:
var myNinjaApp = angular.module('myNinjaApp', []);
myNinjaApp.directive('randomNinja', [function(){
return {
restrict: 'E',
scope: {
theNinjas: '=',
title: '='
},
template: '<img ng-src="{{theNinjas[random].thumb}}"/>',
controller: function($scope) {
let length = $scope.theNinjas.length; //$scope.theNinjas is undefined
$scope.random = Math.floor(Math.random() * length);
console.log($scope.random);
}
};
}]);
myNinjaApp.controller('NinjaController', ['$scope', '$http', function($scope, $http) {
$http.get('data/ninjas.json').then(function(data){
$scope.ninjas = data.data;
});
}]);
还有这个 index.html 文件:
<!DOCTYPE html>
<html lang="en" ng-app="myNinjaApp">
<head>
<title>TheNetNinja Angular Playlist</title>
<link href="content/css/styles.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-route/1.7.9/angular-route.min.js"></script>
<script src="app\app.js"></script>
</head>
<body ng-controller="NinjaController">
<random-ninja the-ninjas="ninjas" title="'Random Ninja'"></random-ninja>
</body>
</html>
我注意到在指令的控制器代码中,$scope.theNinjas 未定义,但 title 未定义。
当我调试代码时,我可以看到在读取$scope.theNinjas.length 之后调用了$http.get()。
如何获取指令控制器中数组的长度?
【问题讨论】:
标签: javascript angularjs angularjs-directive angularjs-1.6