服务 - 无法读取未定义的属性

时间:2014-08-21 08:59:10

标签: angularjs

我正在尝试为我的控制器整理服务。但我一直在说错误 "无法阅读财产' industriesArr'未定义"。我很确定我误解了一些基本的东西,所以请教育我。

服务:

angular.module('core').service('FormService', function() {
    var data = {
        'industriesArr': [
            'Alcoholic Drinks','Animals and Pets','Arts and Entertainment',
            'Baby and Toddler','Banking','Beauty and Personal Care','Building and Construction',
            'Clothing and Footwear','Communication Services','Confectionary and Snacks',
            'Dining and Nightlife',
            'Education and Jobs','Electronics and Technology',
            'Family and Community','Fast food and Restaurant','Financial Services','Food and Groceries',
            'Games and Toys','Government and Law',
            'Health','Home and Garden',
            'Insurances','Internet, Telecom and Software',
            'Jewelry and Luxury',
            'Leisure',
            'Media and Publications',
            'News','Non-alcoholic Drinks','Non-profit Organisation',
            'Occasions and Gifts','Office Supplies','Other',
            'Personal Accessories','Pharmaceutical and Medical','Political Organisation','Professional Services','Public Interest',
            'Real Estate','Retail Services and Wholesaler',
            'Sports Accessories','Sports and Fitness',
            'Tobacco','Tourism and Travel','Transport',
            'Utilities',
            'Vehicles'
        ]
    };
    return data;

});

控制器:

angular.module('core').controller('SignupController', ['$scope', 'FormService', function($scope, FormService) {
    $scope.industriesArr = FormService.data.industriesArr;
});]);

HTML就是:

<p ng-repeat="industry in industriesArr">{{industry}}</p>

3 个答案:

答案 0 :(得分:0)

您返回数据的方式应该使用工厂。所以不是这个

angular.module('core').service('FormService', function() {

使用此

angular.module('core').factory('FormService', function() {

使用服务语法时,Angular将其视为构造函数。如果您想使用服务,请执行return并在this上定义您的属性\功能,例如

this.industriesArr=[...];

答案 1 :(得分:0)

像这样写你的模块:

angular.module('core').service('FormService', function() {
    return{
        getData: function() {
           return { 'industriesArr': [...]; }
        }
    }

});

答案 2 :(得分:0)

犯了一个愚蠢的错误,并在将FormService与我的控制器关联时将其置于错误的顺序。