Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject mathjs into Angular.js?

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.

like image 764
stevek-pro Avatar asked Apr 30 '26 04:04

stevek-pro


2 Answers

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
like image 166
Michael P. Bazos Avatar answered May 04 '26 03:05

Michael P. Bazos


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);
    }
}
like image 36
jmgonet Avatar answered May 04 '26 02:05

jmgonet