robotsushi robotsushi - 4 months ago 11
AngularJS Question

Include 3rd-party Javascript Libraries into an AngularJS app

I'm trying to include a javascript libraries (actually, a handfull) into my AngularJS app. So far, I am building a stripped down version of this app, with no design. It's just all about functionality and data processing at this point.

This is the first javascript library I'm attempting to add into my AngularJS app: https://github.com/LarryBattle/Ratio.js

At first, I tried to simply include it into my HTML file using script src tag, but when I try to use it inside my controller, I receive this error: ReferenceError: require is not defined

I've read that it's best to convert javascript libraries into services or directives or even filters when using AngularJS. Can anyone provide any insight on the best way to do this? Or perhaps some relevant tutorials? I have not been able to find one that is simple enough to apply to my needs. Can anyone help or provide some direction with this? Here's my code so far:

<html ng-app="myApp">
<head>
<title>PercentCalc App</title>
</head>
<body ng-controller="MainCtrl">

Amount: <input type="number" ng-init="amountone=28" ng-model="amountone"> Value: <input type="number" ng-init="valueone=300" ng-model="valueone">
<br />
Amount: <input type="number" ng-init="amounttwo=3.5" ng-model="amounttwo"> Value: <input type="number" ng-init="valuetwo=50" ng-model="valuetwo">
<br /><br />
=========================
<br /><br />
Test ratio: {{ amountone }}/{{ amounttwo}} = {{ ratioone() }} OR {{ ratioonestring }}<br />
Test ratio: {{ amounttwo }}/{{ amountone}} = {{ ratiotwo() }}<br />

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<script type="text/javascript" src="js/ratio.js"></script>
<script type="text/javascript" src="js/percentcalc-ng-one.js"></script>

</body>
</html>


===

//percentcalc-ng-one.js
'use strict';

var app = angular.module('myApp', []);

app.controller('MainCtrl', function ($scope) {
console.log($scope);
var Ratio = require("lb-ratio"); // <--- this is where the error is thrown
$scope.ratioone = function () { return $scope.amountone / $scope.amounttwo; }
$scope.ratiotwo = function () { return $scope.amounttwo / $scope.amountone; }

$scope.ratioonestring = Ratio.parse( $scope.ratioone() ).simplify().toString();

});


I would really be appreciative if anyone could help direct me on how to include 3rd-party javascript libraries into my AngularJS app. I'd like to be able to add it as a dependency into certain apps, that way I could reuse this feature in other apps. Thanks in advance!

Answer

Comment out var Ratio = require("lb-ratio") and it should work.

When you include the script, Ratio is already on your global scope (of the window, not your controller).

Comments