不能向其他模块注入常数angularjs ionic

时间:2017-01-23 07:04:05

标签: angularjs ionic-framework global-variables constants angular-module

我想使用可以从项目中的任何位置调用的常量变量。

我制作了'constants.js'。

angular.module('myApp.constants', [])

.constant('const', (function(){

  return {
    username = 'abc'
  }
})()
);

'app.js'

angular.module('myApp', ['ionic', 'myApp.controllers', 'myApp.constants'])

.run(function($ionicPlatform, $rootScope) {
  $ionicPlatform.ready(function() {

    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      StatusBar.styleDefault();
    }

  });
})

'controllers.js'

angular.module('myApp.controllers', [])

.controller('LoginCtrl', function($scope, $ionicPopup, $http, $state, const) {
  $scope.user_name = const.username;
});

当我从控制器调用'const'时,我收到了这个错误。

D/SystemWebChromeClient: file:///android_asset/www/js/controllers.js: Line 8 : Uncaught SyntaxError: Unexpected token const
I/chromium: [INFO:CONSOLE(8)] "Uncaught SyntaxError: Unexpected token const", source: file:///android_asset/www/js/controllers.js

我不熟悉angularjs及其模块。 我希望有人能把我送到正确的方向。

提前致谢。

2 个答案:

答案 0 :(得分:0)

尝试像这样声明你的常量

    var cursor = Template.currentData();
    liveChart = Highcharts.chart(cursor.chart_id, {
        title: {
            text: 'Memory usage of the controlcontainers_mongo_1'
        },
        xAxis: {
            type: 'datetime',
        },
        yAxis: {
            title: {
                text: 'usage'
            },
            labels: {
                 formatter: function() {
                     //This will round the value, but you can do anything to this value now
                     return this.value.toFixed(2);
                 }
            },
        },
        tooltip: {
            formatter: function() {
                return '<b>' + this.series.name + '</b><br/>' + Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>';
            }
        },
        series: [{
            type: 'line',
            name: 'memory usage',
            data: []
        }]
    });

答案 1 :(得分:0)

angular.module('myApp.constants', [])

.constant('constantMessage', (function(){
    return {
        username : 'abc'
    }
})());
angular.module('myApp', ['myApp.constants'])
.controller('LoginCtrl', function($scope,constantMessage) {
  $scope.user_name = constantMessage.username;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div  ng-app="myApp" ng-controller="LoginCtrl">
  {{user_name}}
  </div>

请将您的constant.js文件更新为:

.constant('constantMessage', (function(){
    return {
        username : 'abc'
    }
})());

然后检查..