AngularJS - 将服务与控制器一起使用

AngularJS - Use Service with Controller

我在 AngularJS 中编写了一个服务,但我没有在我的控制器中使用该服务。

Service.js

var appService = angular.module("appService", []);
appService.service("bddService", function() {

    var bdds = bdd;

    this.getBdds = function(){
        return bdds;
    };

    var bdd = [{
        id : 1,
        nom : "Activité commercial",
        desc : "Information de l'activité commercial de l'entreprise Bou."
    }];
});

Controller.js

(function(){
    var accueilCtrl = angular.module("accueilCtrl", ['appService']);

    accueilCtrl.controller('accueilCtrl', ['$scope', 'bddService', function($scope, bddService){

        $scope.bdds = bddService.getBdds(); // No error, but no data

    }]);
})();

有两个文件,如果我将代码放在同一个文件中它就可以工作 (Service injection into controller with AngularJS)。控制台不显示错误。

var bdds = bdd;

this.getBdds = function(){
    return bdds;
};

var bdd = [{
    id : 1,
    nom : "Activité commercial",
    desc : "Information de l'activité commercial de l'entreprise Bou."
}];

由于 javascript

中的可变提升概念,这将变成如下所示
var bdd;
var bdds;
bdds = bdd;              // makes bdds undfined

this.getBdds = function(){
    return bdds;
};

bdd = [{
    id : 1,
    nom : "Activité commercial",
    desc : "Information de l'activité commercial de l'entreprise Bou."
}];

所以这样做

var bdd = [{
    id : 1,
    nom : "Activité commercial",
    desc : "Information de l'activité commercial de l'entreprise Bou."
}];
var bdds = bdd;

this.getBdds = function(){
    return bdds;
};