简体   繁体   English

Angularjs在指令中获取数据

[英]Angularjs get data in directive

i'm writing a blog by AngularJs. 我正在写一篇AngularJs的博客。 i'm new in it. 我是新手。 I'm create a BlogController and BlogData Service. 我正在创建一个BlogController和BlogData服务。 BlogController use BlogData. BlogController使用BlogData。 BlogData use $http and get data from server. BlogData使用$ http并从服务器获取数据。 my controller like this; 我的控制器是这样的;

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

blogData service like this; 像这样的blogData服务;

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). 我正在为pageniation创建一个指令(指令使用jquery分页库)。 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. 指令工作正常,但onPageClick上的帖子未定义。 why it is not work? 为什么不行?

As mentioned in the comments, scope.$apply() is needed because the jQuery plugin callback runs "outside" Angular. 正如评论中提到的那样,范围。$ apply()是必需的,因为jQuery插件回调在“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. 换句话说,onPageClick()回调在没有Angular知道的情况下发生,因此即使更新了scope.blogPosts,Angular也不会注意到范围更新。

So, the fix is to add scope.$apply() after scope.blogPosts = posts; 因此,修复是在scope.blogPosts = posts;之后添加scope.$apply() scope.blogPosts = posts; to cause Angular to run a digest cycle, which will cause the view to update. 使Angular运行摘要周期,这将导致视图更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM