1

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.

Shahzad Ahamad
  • 809
  • 1
  • 11
  • 30
  • 5
    `faqData` is an object. `$scope.faqData = {};`. Unless your service is mutating it. [Slice](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) is a method available to arrays. (even though technically an array is an object with numeric property keys and a special relationship with `length` but you get my point) – ste2425 Apr 20 '16 at 11:20
  • 1
    @ste2425 My service is mutating it. Here `.factory('Faq', function ($http) { return { get: function () { console.log("inside function"); return $http.get('/Json/faq.json'); } }; })` . The service is giving back an array of objects – Shahzad Ahamad Apr 20 '16 at 11:25
  • 1
    Has your promise resolved by the time your watcher fires? Maybe you should default your `faqData` variable to the type you intend to use with it. If the watch is fired before the promise resolves you will be trying to call `.slice` on an object as it hasn't been mutated at that point. – ste2425 Apr 20 '16 at 11:31
  • 2
    @ste2425 You are rightmy watcher was firing before my promise was getting resolved. Thank you. – Shahzad Ahamad Apr 20 '16 at 11:39
  • If that solved your issue ill add it as an answer for others in the future. – ste2425 Apr 20 '16 at 11:40

1 Answers1

2

.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

ste2425
  • 4,656
  • 2
  • 22
  • 37