简体   繁体   中英

How to use slice() method pn object array in angularJS

I am trying to use slice() method on an object array in AngularJS but its says 'slice is not a method'.

Here is the code

.controller('AppCtrl', function ($scope, Faq) {

    $scope.filteredFaqData = [];
    $scope.currentPage = 1;
    $scope.numPerPage = 5;
    $scope.maxSize = 3;
    $scope.faqData = {};
    Faq.get().then(function (msg) {
        $scope.faqData = msg.data;

    });
    $scope.$watch('currentPage + numPerPage', function () {
        var begin = (($scope.currentPage - 1) * $scope.numPerPage)
        , end = begin + $scope.numPerPage;

        $scope.filteredFaqData = $scope.faqData.slice(begin, end);
    });

});

I am getting the data from json file in $scope.faqData using a service and it is working.

But slice method is not working in the console it is giving error "$scope.faqData.slice" is not a method.

.slice is a method available from the array prototype.

Your faqData is defined as a plain 'ol object. As such it does not have access to .slice .

Your service is mutating faqData into an array however giving you access to .slice , this is only when it resolves.


So, the issue is your watcher may fire before your promise resolves meaning your trying to call slice from a plain object.

You should define your objects to the type you will be using them with, avoid mutating objects where possible.

Your watch may also need to handle the fact your promise has not resolved yet, that depends on what you intend to do in the watcher.

slice docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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