Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs: scope.data is undefined inside directive

Tags:

angularjs

First off, i found the api address from this topic: Laravel 4 and Angular JS and Twitter Bootstrap 3 Pagination

Now i am working about this, my little script is so:

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 see, console.log(scope) inside directive is shows a lot of things in console, especially i see allData there with lots data, but if i change it to

console.log(scope.allData)

it prints undefined..

i don't understand why. how can i solve this? thanks.

like image 990
yigitozmen Avatar asked Jan 11 '14 18:01

yigitozmen


1 Answers

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

So, why do you see the data when logging the scope object instead ?

At the time the object is logged it has no property allData (and no data).
But by the time you go over to the console and expand the node and look for 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 in e.g. ng-repeat you don't have to worry: You can use it normally (as if it were defined) and Angular will automatically "pick it up" as soon as it arrives and do stuff.
Yet, if you want (for your own mysterious reasons) to get informed when it is ready, your can use $watch:

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

See, also, this short demo.

like image 116
gkalpak Avatar answered Sep 30 '22 11:09

gkalpak