Angularjs: scope.data is an undefined internal directive

Firstly, I found the api address from this thread: Laravel 4 and Angular JS and Twitter Bootstrap 3 Pagination

Now I'm working on this, my little script is this:

var app = angular.module('kategori', [ 'ngResource', 'apiBaseRoute' ]); app.factory('Data', ['$resource', 'apiBaseRoute', function($resource, config){ return $resource('http://develop.alexei.me/careers/careers.php?callback=JSON_CALLBACK&page=:page', { page: 1 }, { 'get': { method: 'JSONP' } }); }]); app.controller('KategoriListCtrl', function($scope, Data){ $scope.init = function() { Data.get({}, function(response){ $scope.kategoriList = response.careers; },function(error){ console.log("HATA VAR" + error); }); }; }); app.directive('paginate', function(){ return{ scope:{ allData: '=paginate2' }, link: function(scope){ console.log(scope); } } }); 

And this is the html side:

  <div class="col-md-6 col-md-offset-3" ng-controller="KategoriListCtrl" ng-init="init()"> {{kategoriList}} <div paginate paginate2="kategoriList"></div> </div> 

as you can see, console.log (scope) inside the directive shows a lot of things in the console, especially I see allData there with big data, but if I change it to

 console.log(scope.allData) 

it prints undefined ..

I do not understand why. how can i solve this? thanks.

+6
source share
1 answer

By the time JS reaches your console.log , the allData property allData undefined (since kategoriList is undefined). kategoriList (and therefore allData ) is created (and populated with lots of data) asynchronously at a later time.

So why do you see data when registering a scope object?

During registration of an object, it does not have the allData property (and no data).
But by the time you go to the console and expand node and find the allData property, the property has been added and populated by your AJAX call (using $resource ).


It is not clear what you want to do with allData .
If you want to use it, for example. ng-repeat you don’t need to worry: you can use it as usual (as if it were defined), and Angular will automatically β€œpick it up” as soon as it comes and does something.
However, if you want (for your own mysterious reasons) to get information when it is ready, you can use $watch :

 scope.$watch('allData', function(newValue) { if (newValue !== undefined) { console.log(scope.allData); } }); 

See also this short demo .

+19
source

All Articles