3

How can I inject mathjs into Angular.js?

I can't get it to work - I used bower install mathjs --save to install it.

Update: The JS min file is properly injected into index.html

Do I need to inject it into the main module or into the controller? I tried both and got a white screen on page load with an error message about the non-availability of the module.

1
  • You do not need to inject in any module because angular will not treat it as dependency.. check mathjs.org can you tell me how are u loading math.js?
    – Ravi Sahu
    Commented Mar 16, 2015 at 10:28

2 Answers 2

5

Step 1

bower install mathjs --save

Step 2

Reference mathjs in your main html page

<script src="path/to/bower_components/mathjs/dist/math.min.js" type="text/javascript"></script>

Step 3

This dependency is not angular-aware, there is no module to inject as a dependency of your angular application. As mathjs exposes a global math object, you can use it in an angular component as follows :

math.round(0.123, 2) // gives back 0.12
2
  • Nah, my GruntFile already took care of injection into index.html. How can I access this now in a controller?
    – Stephan K.
    Commented Mar 16, 2015 at 10:54
  • mathjs exposes a global math object, so you should be able to play with it in your components.
    – Michel
    Commented Mar 16, 2015 at 10:59
5

As time passed, I'm adding this updated response.

If you're using Angular, chances are that you're using npm as well. To add mathjs, you can follow the official procedure

npm install mathjs
npm install @types/mathjs

The two above commands will update the package.json and package-lock.json as needed.

Then, as described in the Getting Started, you need to import separately each of the mathjs commands you want to use. So, for example, to perform square root in a typescript class:

import { sqrt } from 'mathjs';


export class MyClass {
    function calculate(n: number): number {
        return sqrt(n);
    }
}
1

Not the answer you're looking for? Browse other questions tagged or ask your own question.