0

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?

13
  • 3
    the problem could be this.currentPage. I don't see where it is Commented Aug 30, 2013 at 13:23
  • @baris Where is the code of onPageClick??? Commented Aug 30, 2013 at 14:05
  • I deleted my answer about promises since ganaraj and Khanh TO pointed out that the premise of the answer was actually false, to avoid any confusion. Commented Aug 30, 2013 at 14:05
  • @khanh TO; i delete this.CurrentPage and put 2 in here. Also This not work. Commented Aug 30, 2013 at 14:17
  • @sza; onPageClick in directive defination Commented Aug 30, 2013 at 14:18

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.