<ion-infinite-scroll>调用连续

时间:2016-09-28 05:47:07

标签: angularjs ionic-framework

我正在开发一个使用离子的新闻应用程序。对于不同类别的新闻我使用相同的模板文件和控制器功能。我的控制器功能如下。我使用离子无限循环来检索旧消息,我的回调函数是loadMore()。我第一次调用类别时我的代码工作正常,但是当我调用其他类别同时loadMore()连续调用时,作为无限循环。

.controller('categoryCtrl', ['$scope', '$http', '$stateParams', '$location', '$state',
        function ($scope, $http, $stateParams, $location, $state, $ionicHistory) {

            $scope.category = $location.path().split('/')[2];
            $scope.articles = [];
            $scope.last_id = 0;
            $http({
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                data: {'path': $location.path(), 'id': ''},
                method: 'POST',
                url: 'http://www.example.com/article/mobile_api/category',
            }).success(function (newsData) {

                angular.forEach(newsData, function (newsArticle) {
                    $scope.articles.push(newsArticle);
                    $scope.last_id = newsArticle.article_id;
                });
            }).error(function (data) {
                alert('Warning! Home Page Request failed');
            });
            $scope.loadMore = function () {
                $http({
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    data: {'path': $location.path(), 'id': $scope.last_id},
                    method: 'POST',
                    url: 'http://www.example.com/article/mobile_api/category',
                }).success(function (newsData) {

                    angular.forEach(newsData, function (newsArticle) {
                        $scope.articles.push(newsArticle);
                        $scope.last_id = newsArticle.article_id;
                    });

                              $scope.$broadcast('scroll.infiniteScrollComplete');

                });
            };

        }]);

HTML CODE GIVEN BELWOW

<ion-content class="has-header bar-positive" padding="true">

    <div class="list" ng-repeat="item in articles" style="margin-bottom: 5px;">
        <a  ng-click="">
            <div class="row" >
                <div class="col col-25"> <img width="100%" src="{{pic_path}}{{item.pic_name}}"></div>
                <div class="col col-75 "><p  class="item-body">{{item.article_name}}</p>                        
            </div>

        </a>
    </div>

    <ion-infinite-scroll
        on-infinite="loadMore()"
        distance="1%">
    </ion-infinite-scroll>
</ion-content>

这是我的route.js

angular.module('app.routes', [])  
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider 
.state('example.technology', {
url: '/technology',
views: {
'side-menu21': {
templateUrl: 'templates/category.html',
controller: 'categoryCtrl'
}
}
})
.state('example.wolrd', {
url: '/world',
views: {
'side-menu21': {
templateUrl: 'templates/category.html',
controller: 'categoryCtrl'
}
}
})
$urlRouterProvider.otherwise('/side-menu21/home') 
});

3 个答案:

答案 0 :(得分:0)

如果没有更多可用数据,请删除更多负载,并将距离值增加到“2%”

<div class="list" ng-repeat="item in articles" style="margin-bottom: 5px;">
    <a  ng-click="">
        <div class="row" >
            <div class="col col-25"> <img width="100%" src="{{pic_path}}{{item.pic_name}}"></div>
            <div class="col col-75 "><p  class="item-body">{{item.article_name}}</p>                        
        </div>

    </a>
</div>

<ion-infinite-scroll
   ng-if="moreDataAvailable"
    on-infinite="loadMore()"
    distance="2%">
</ion-infinite-scroll>

<强>控制器

.controller('categoryCtrl', ['$scope', '$http', '$stateParams', '$location', '$state',
        function ($scope, $http, $stateParams, $location, $state, $ionicHistory) {

            $scope.category = $location.path().split('/')[2];
            $scope.articles = [];
            $scope.last_id = 0;
            $http({
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                data: {'path': $location.path(), 'id': ''},
                method: 'POST',
                url: 'http://www.example.com/article/mobile_api/category',
            }).success(function (newsData) {

                angular.forEach(newsData, function (newsArticle) {
                    $scope.articles.push(newsArticle);
                    $scope.last_id = newsArticle.article_id;
                });
            }).error(function (data) {
                alert('Warning! Home Page Request failed');
            });
            $scope.loadMore = function () {
                $http({
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    data: {'path': $location.path(), 'id': $scope.last_id},
                    method: 'POST',
                    url: 'http://www.example.com/article/mobile_api/category',
                }).success(function (newsData) {
    // set it to false if no more data to load
    if(!newsData){
    $scope.moreDataAvailable = false;
    }
                    angular.forEach(newsData, function (newsArticle) {
                        $scope.articles.push(newsArticle);
                        $scope.last_id = newsArticle.article_id;
                    });

                              $scope.$broadcast('scroll.infiniteScrollComplete');

                });
            };

答案 1 :(得分:0)

请尝试以下:

一些不同的方法,但适当的方法:

<强> Contoller.js

public class MainActivity extends  Activity {


    boolean isFromClicked = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setCurrentTimeOnView();
        addListenerOnButton();

    }

    // display current time
    public void setCurrentTimeOnView() {

        tvDisplayTime = (TextView) findViewById(R.id.tvTime);
        tvDisplayTime1 = (TextView) findViewById(R.id.tvTime1);
        //  timePicker1 = (TimePicker) findViewById(R.id.timePicker1);

        final Calendar c = Calendar.getInstance();
        hour = c.get(Calendar.HOUR_OF_DAY);
        minute = c.get(Calendar.MINUTE);

        // set current time into textview
        tvDisplayTime.setText(new StringBuilder().append(pad(hour)).append(":")
                .append(pad(minute)));
        tvDisplayTime1.setText(new StringBuilder().append(pad(hour)).append(":")
                .append(pad(minute)));

    }

    public void addListenerOnButton() {

        btnChangeTime = (Button) findViewById(R.id.btnChangeTime);
        btnChangeTime1 = (Button) findViewById(R.id.btnChangeTime1);

        btnChangeTime.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                showDialog(TIME_DIALOG_ID);
                isFromClicked = false;

            }

        });


        btnChangeTime1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                showDialog(TIME_DIALOG_ID);
                isFromClicked = true;

            }

        });

    }



    private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int selectedHour,
                              int selectedMinute) {
            hour = selectedHour;
            minute = selectedMinute;

                if ( isDateToSelected )
                    tvDisplayTime1.setText(new StringBuilder().append(pad(hour))
                    .append(":").append(pad(minute)));
                else
                    tvDisplayTime.setText(new StringBuilder().append(pad(hour))
                    .append(":").append(pad(minute)));
        }
    };

}
在factories.js中

.controller('categoryCtrl', ['$scope', '$http', '$stateParams', '$location', '$state',
function ($scope, $http, $stateParams, $location, $state, $ionicHistory, getData) {

    $scope.category = $location.path().split('/')[2];
    $scope.articles = [];
    $scope.last_id = 0;
    $scope.app.loadMoreData = true;


    $scope.loadMore = function () {
    var id = $scope.last_id;
    getData.getAllData(id).then(function(result){
        if(!result){
            $scope.app.loadMoreData = false;
            return;
        }
        angular.forEach(newsData, function (newsArticle) {
            $scope.articles.push(newsArticle);
            $scope.last_id = newsArticle.article_id;
        })
        $scope.$broadcast('scroll.infiniteScrollComplete');
     }) 
    };

}]);

in html

.factory('getData', function($http) {
  return {
    getAllData: function(id) {
      return $http.get('http://www.example.com/article/mobile_api/category?id=' + id);
    }
  }
})

答案 2 :(得分:0)

app.js

angular.module('app', ['ionic', 'app.controllers', 'app.routes', 'app.directives','app.services',])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
  cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
  cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
  // org.apache.cordova.statusbar required
  StatusBar.styleDefault();
}
});
})

services.js

angular.module('app.services', [])

 .factory('getData', [function($http){
 return {
 getAllData: function(id) {
      return $http.get('http://localhost/article/mobile_api/category?id=' + id);
}
}
}]);

controller.js

angular.module('app.controllers', [])
.controller('categoryCtrl', ['$scope', '$http', '$stateParams', '$location', '$state', // 
function ($scope, $http, $stateParams, $location, $state, $ionicHistory,getData) {



            $scope.articles = [];
            $scope.last_id = 0;
            $scope.loadMoreData = true;


            $scope.loadMore = function () {
                var id = $scope.last_id;
                getData.getAllData(id).then(function (result) {
                    if (!result) {
                        $scope.app.loadMoreData = false;
                    }
                    angular.forEach(result, function (newsArticle) {
                        $scope.articles.push(newsArticle);
                        $scope.last_id = newsArticle.article_id;
                    })
                    $scope.$broadcast('scroll.infiniteScrollComplete');
                })
            };

  }]);