I'm using this app.js file:
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;
});
}]);
and this index.html file:
<!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>
I noticed in the directive's controller code, the $scope.theNinjas
is undefined, but the title
isn't.
When I debug the code, I can see the $http.get()
call is made after the $scope.theNinjas.length
is read.
How can I get the length of the array in the directive's controller?