在具有服务的控制器之间共享数据(AngularJS)

时间:2015-04-06 12:31:22

标签: javascript angularjs

我想建立一个支持多种语言的网站。所以我想使用AngularJS控制器来控制视图。我写了一些脚本,但是我收到以下错误: TypeError:无法读取属性' getLang'未定义的

这是我的AngularJS代码:

var myApp = angular.module('myApp',[]);
myApp.service('languageService' , function() {
    var language = 'en';
    return {
        getLang: function() {
            return language;
        },

        setLang: function(ind) {
              if (ind == 0) {
                  language = 'en';
              } else if (ind == 1) {
                  language = 'ru';
              }
        }
    };
})

myApp.controller('ChangeLangCtrl', ['$scope', function($scope, languageService) {
     $scope.changeLang = function(ind) {
        languageService.setLang(ind);
     }
}])

myApp.controller('NaviCtrl', ['$scope', function($scope, languageService) {
    var currentLang = languageService.getLang();
    if (currentLang == 'en') {
        $scope.menu = ['About Us', 'Service', 'Contacts'];
    } else {
        $scope.menu = ['О нас', 'Наши Услуги', 'Связь с нами']
    }
}])

那么我的错误是什么?我的意思是,我在开头用en初始化语言变量。那么为什么getLang()函数未定义?

2 个答案:

答案 0 :(得分:2)

['$scope', function($scope, languageService) 

你没有;指定languageService

一定是

['$scope', 'languageService', function($scope, languageService) 

因为您没有为languageService.getLang指定任何值而导致languageService未被定义,因此getLang没有为myApp.controller('ChangeLangCtrl', [['$scope', 'languageService', function($scope, languageService) { $scope.changeLang = function(ind) { languageService.setLang(ind); } }]) myApp.controller('NaviCtrl', ['$scope', 'languageService', function($scope, languageService) { var currentLang = languageService.getLang(); if (currentLang == 'en') { $scope.menu = ['About Us', 'Service', 'Contacts']; } else { $scope.menu = ['О нас', 'Наши Услуги', 'Связь с нами'] } }]) 退出。

所以你的代码将成为:

{{1}}

答案 1 :(得分:0)

You forget to inject languageService as a dependency in your controller,thats why its throwing that error.

Try this,

var myApp = angular.module('myApp',[]);
myApp.service('languageService' , function() {
    var language = 'en';
    return {
        getLang: function() {
            return language;
        },

        setLang: function(ind) {
              if (ind == 0) {
                  language = 'en';
              } else if (ind == 1) {
                  language = 'ru';
              }
        }
    };
})

myApp.controller('ChangeLangCtrl', ['$scope','languageService', function($scope, languageService) {
     $scope.changeLang = function(ind) {
        languageService.setLang(ind);
     }
}])

myApp.controller('NaviCtrl', ['$scope','languageService', function($scope, languageService) {
    var currentLang = languageService.getLang();
    if (currentLang == 'en') {
        $scope.menu = ['About Us', 'Service', 'Contacts'];
    } else {
        $scope.menu = ['О нас', 'Наши Услуги', 'Связь с нами']
    }
}])