角度推入数组给出:TypeError:无法读取属性'推'的未定义

Angular pushing into an array gives: TypeError: Cannot read property 'push' of undefined

本文关键字:读取 属性 未定义 TypeError 数组      更新时间:2023-09-26

我正试图将文本框中的详细信息推送到AngularJS中的数组中。但它不起作用

AppName.factory('sampleFactory', function(){
        var customerdetails=[
                {name:'John Smith', country:'Denmark', worth:'5000000'},
                {name:'John Lewis',country:'England',worth:'10000000'},
                {name:'Rick Evans',country:'America',worth:'6000000'}
            ];
        var factory={};
        factory.getCustomers=function(){
            return customerdetails;
        };
        return factory;
    });
AppName.controller('homeController', function($scope, sampleFactory){
    $scope.customers= sampleFactory.getCustomers();
    $scope.addCustomer = function(){
        $scope.customerdetails.push({
            name:$scope.customerName, 
            country:$scope.customerCountry,
            worth:$scope.customerWorth
        });
    };
});

该页面有一个按钮,其中ng-click="addCustomer"。但它不会添加到数组中。

工厂的零件运转良好。我确信我在addCustomer函数中犯了一个错误。有人能发现吗?谢谢

您使用了错误的变量名,它应该是$scope.customers:

$scope.addCustomer = function(){
        $scope.customers.push({
            name:$scope.customerName, 
            country:$scope.customerCountry,
            worth:$scope.customerWorth
        });
    };

您将其误认为是服务的变量名。