0

I'm would like to use a var from a plain old javascript file in an AngularJS constant. Is that possible. Below is what I have tried.

Javascript file:

"use strict";

var CONST_MAP = {
  'key': 'value'
};

AngularJS file:

'use strict';

angular.module('foo').constant('bar', {
    'test': CONST_MAP
});
1
  • Sorry, not an answer, but I was just wondering why you would use var instead of const. Commented Nov 19, 2021 at 13:00

2 Answers 2

1

It's possible using angular providers.

var CONST_MAP = {
  'key': 'value'
};
var app = angular.module('myApp', []);
app.constant('bar', {
  'test': CONST_MAP
})
app.controller('myCtrl', function ($scope, bar) {
  console.log(bar)
  $scope.name = bar.test.key;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  {{ name }}
</div>

Sign up to request clarification or add additional context in comments.

6 Comments

But I want my javascript var in a separate file.
You can import them to your file and use it
How do I import the javascript file?
You can import with import { CONST_MAP } from "./path/to/your/file" and the same variable must be exported from the file as export var CONST_MAP = { 'key': 'value' }
I get the following error: >> error: couldn't process source due to parse error >> 'import' and 'export' may appear only with 'sourceType: module'
|
0

I think that you can do it like this:

angular.module('foo').constant('bar', (function(){
    var CONST_MAP = {
      'key': 'value'
    };
    return {
       test: CONST_MAP
    }
}));

2 Comments

But I want my javascript var in a separate file.
Aham, than check the answer from @Nitheesh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.