【问题标题】:AngularJS - Use Service with ControllerAngularJS - 将服务与控制器一起使用
【发布时间】:2015-05-10 04:04:06
【问题描述】:

我在 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)。控制台不显示错误。

【问题讨论】:

  • 让我们看看你是如何在你的 html 中加载你的 js 的。

标签: javascript angularjs service controller


【解决方案1】:
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;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-06
    • 2015-02-02
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    相关资源
    最近更新 更多