Baris
Baris

Reputation: 455

Angularjs get data in directive

i'm writing a blog by AngularJs. i'm new in it. I'm create a BlogController and BlogData Service. BlogController use BlogData. BlogData use $http and get data from server. my controller like this;

barbarapp.controller('BlogController', function ($scope, blogData) {
    $scope.blogPosts = blogData.getBlogPosts(0);
});

blogData service like this;

barbarapp.factory('blogData', function ($http, $q) {
    return {
        getBlogPosts: function (pageNumber) {
            debugger;
            var deferred = $q.defer();
            $http({
                url: 'Blog/GetBlogPosts',
                method: 'POST',
                data: { 'pageNumber': pageNumber }
            }).success(function (response) {
                deferred.resolve(response.posts);
            });
            return deferred.promise;
        }
    };
});

it is works fine. And i'm create a directive for pageniation (directive use a jquery pagination library). pagination directive like this;

barbarapp.directive('createPagination', function (blogData, $q) {
    return function (scope, element) {        
        $(element).pagination({
            items: scope.postCount,
            itemsOnPage: scope.itemsOnPage,
            cssStyle: "light-theme",
            onPageClick: function () {
                var posts = blogData.getBlogPosts(this.currentPage);
                scope.blogPosts = posts;
            }
        });
    };
});

directive works fine but posts on onPageClick it's undefined. why it is not work?

Upvotes: 0

Views: 1640

Answers (1)

Mark Rajcok
Mark Rajcok

Reputation: 364677

As mentioned in the comments, scope.$apply() is needed because the jQuery plugin callback runs "outside" Angular. In other words, the onPageClick() callback happens without Angular knowing, so even though scope.blogPosts is updated, Angular doesn't notice the scope update.

So, the fix is to add scope.$apply() after scope.blogPosts = posts; to cause Angular to run a digest cycle, which will cause the view to update.

Upvotes: 2

Related Questions