如何在angularJS中使用slice

如何在angularJS中使用slice

本文介绍了如何在angularJS中使用slice()方法pn对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在AngularJS的对象数组上使用slice()方法,但是它说'slice不是方法'.

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

这是代码

.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);
    });

});

我正在使用服务从 $ scope.faqData 中的json文件中获取数据,并且可以正常工作.

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

但是切片方法在控制台中不起作用,它给出了错误"$ scope.faqData.slice" 不是方法.

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

推荐答案

.slice 是数组原型中提供的一种方法.

.slice is a method available from the array prototype.

您的 faqData 被定义为普通的'ol对象.因此,它无权访问 .slice .

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

您的服务正在将 faqData 突变为数组,但是仅在解析时才允许您访问 .slice .

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

因此,问题是您的观察者可能会在您的诺言解决之前解雇,这意味着您试图从一个普通对象中调用 slice .

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.

切片文档

这篇关于如何在angularJS中使用slice()方法pn对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 14:54